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 possibl
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 equals
method is defined in terms of equality of that String
property, and if the hashCode
method is also implemented correctly, then you can use the hashSet.contains to find an object with the correct value in O(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