How to check in java if Set contains object with some string value?(如果 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.contains 在 O(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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果 Set 包含具有某些字符串值的对象,如何检查
基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java Swing计时器未清除 2022-01-01
