如果 Set 包含具有某些字符串值的对象,如何检查

时间:2023-02-25
本文介绍了如果 Set 包含具有某些字符串值的对象,如何检查 java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组对象.每个对象都有 String 值.

I have Set of objects. Each object has String value.

我需要选择所有 this 值等于direction"的对象.

I need to select all objects that have this value equal to "direction".

是否可以不迭代集合?

推荐答案

一般来说,没有.您需要遍历集合并检查每个对象以查看属性是否等于您正在搜索的值.这是一个 O(n) 操作.

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.

在一种情况下,您无需迭代即可完成.如果您的对象的 equals 方法是根据该 String 属性的相等性定义的,并且如果 hashCode 方法也正确实现,那么您可以使用 hashSet.containsO(1) 时间内找到具有正确值的对象,而无需遍历集合.

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.

您可能还想考虑其他更适合您的用例的集合.例如,如果您使用 Guava,那么您可以考虑使用 多地图.

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.

相关

  • HashMap在同一个键下有多个值

这篇关于如果 Set 包含具有某些字符串值的对象,如何检查 java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:带有迭代器的 java.util.ConcurrentModificationException 下一篇:Java“为"语句实现防止垃圾收集

相关文章

最新文章