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

How to check in java if Set contains object with some string value?(如果 Set 包含具有某些字符串值的对象,如何检查 java?)
本文介绍了如果 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reliable implementation of PBKDF2-HMAC-SHA256 for JAVA(PBKDF2-HMAC-SHA256 for JAVA 的可靠实现)
Correct way to sign and verify signature using bouncycastle(使用 bouncycastle 签名和验证签名的正确方法)
Creating RSA Public Key From String(从字符串创建 RSA 公钥)
Why java.security.NoSuchProviderException No such provider: BC?(为什么 java.security.NoSuchProviderException 没有这样的提供者:BC?)
Generating X509 Certificate using Bouncy Castle Java(使用 Bouncy Castle Java 生成 X509 证书)
How can I get a PublicKey object from EC public key bytes?(如何从 EC 公钥字节中获取 PublicKey 对象?)