如何检查java如果Set包含一些字符串值的对象? [英] How to check in java if Set contains object with some string value?

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

问题描述

我有一套对象。每个对象都有String值。



我需要选择所有这个值等于direction的对象。



是否可以不迭代集?



谢谢。

解决方案

您需要迭代集合并检查每个对象以查看属性是否等于您要搜索的值。这是一个 O(n)操作。



有一种情况可以在没有迭代的情况下执行。如果您的对象的等于方法是根据 String 属性的相等性定义的,而如果 hashCode 方法也正确实现,那么您可以使用 hashSet.contains 以在 O(1)中找到具有正确值的对象)时间,而不需要遍历集合。



正如我所提到的,这是一个非常具体的用例,而不是一般的解决方案。如果字符串是某种唯一的标识符,那么这可能是有用的,但是对于您的具体用例来说,它不起作用。



您可能还要考虑其他集合将更适合您的用例。例如,如果您使用Guava,那么您可以考虑使用 Multimap



相关




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 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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆