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

I know there are a contains(Object o) but i want to check with the attributes of my Object.

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

Thank you.

Jon Skeet
people
quotationmark

Does your User class override equalsusing just the ID? If so, you could use:

if (mySet.contains(new User(1, "irrelevant"));

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.

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.

people

See more on this question at Stackoverflow