检查对象集是否包含具有此属性的对象 [英] Check if Set of Object contain an Object with this attribute
问题描述
考虑我有一个对象列表,我将它转换为一个集合以执行如下操作:
Consider i have a List Of Objects, and i convert it to a Set to make some actions like this :
List<User> listUser = new ArrayList<>();
listUser.add(new User(1, "user1"));
listUser.add(new User(2, "user2"));
listUser.add(new User(3, "user3"));
Set<User> myset = new HashSet<>(listUser);
我知道有一个 contains(Object o)
但我想检查我的对象的属性.
I know there are a contains(Object o)
but i want to check with the attributes of my Object.
我的问题是检查 Set 是否包含具有 ID = 1
或 user = "user1"
或任何属性的对象的最佳方法是
My Question is What is the best way to check if the Set contain an Object with ID = 1
or user = "user1"
or any attribute
谢谢.
推荐答案
您的 User
类是否仅使用 ID 覆盖 equals
?如果是这样,您可以使用:
Does your User
class override equals
using just the ID? If so, you could use:
if (mySet.contains(new User(1, "irrelevant"));
请注意,有一个叫做 mySet
的东西很奇怪,它实际上是一个 List
而不是 Set
...我会考虑更改名称或类型.如果您使用 HashSet
,您将需要覆盖 hashCode
以及 equals
,但无论如何您都应该这样做以遵守 hashCode
代码>对象代码>.
Note that it's quite odd to have something called mySet
which is actually a List
rather than a Set
... I'd consider either changing the name or the type. If you use HashSet
you'll need to override hashCode
as well as equals
, but you should do that anyway to obey the normal contracts from Object
.
如果您希望能够通过多个不同的属性进行检查 - 或者如果您不想覆盖 User
中的相等性 - 那么您可以考虑创建映射,例如
If you want to be able to check by multiple different attributes - or if you don't want to override equality in User
- then you could consider creating maps instead, e.g.
Map<Integer, User> usersById = new HashMap<>();
Map<String, User> usersByName = new HashMap<>();
...
当然,您需要保持所有地图同步 - 您还需要考虑如果有多个同名用户等情况会发生什么.
Then you need to keep all the maps in sync, of course - and you need to consider what happens if you've got multiple users with the same name, etc.
这篇关于检查对象集是否包含具有此属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!