How to check in java if Set contains object with some string value?

后端 未结 6 1518
北荒
北荒 2020-12-16 10:19

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

6条回答
  •  天涯浪人
    2020-12-16 11:08

    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

    • HashMap with multiple values under the same key

提交回复
热议问题