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?
Thanks.
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?
Thanks.
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 thatString
property, and if thehashCode
method is also implemented correctly, then you can use thehashSet.contains
to 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
I know this is an old question, but...
Short answer: NO, it's not possible...
Using
equals()
orcontains()
as recommended by other fellows should be restricted to situations where the attributes you are using for filtering are actually a part of the objects Identity. I don't see any way but a O(n) algorithm.If you are considering native functions, Java 8 brought the Stream API and concepts of Functional Programming, allowing easier and cleaner loop calls. Nonetheless it is worth noting that for your situation all objects in your collection will have to be checked, so complexity will remain O(n).
Example with Java 8's
stream().filter()
Yes this is possible by overwriting the
equals()
method.You just want to check everything works in the equals method.
Code:
Output:
You could also use
Predicate
like in this question to filter the list : What is the best way to filter a Java Collection?