I have Set of objects. Each object has String value.
I need to select all objects that have this value equal to "direction".
Is it possible without iterating over the set?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In general, no. You need to iterate over the set and check each object to see if the property is equal to the value you are searching for. This is an
O(n)operation.There is one situation in which you could do it without iterating. If your object’s
equalsmethod is defined in terms of equality of thatStringproperty, and if thehashCodemethod is also implemented correctly, then you can use thehashSet.containsto find an object with the correct value inO(1)time without requiring iterating over the set.As I mentioned, this is a very specific use case and not a general solution. It might be useful if the string was some sort of unique identifier, but it won’t work for your specific use case.
You might also want to consider other collections that would be better suited to your use case. You could for example if you are using Guava then you could consider using a Multimap.
Related