user5725851
user5725851

Reputation: 69

Find specific object in a List by attribute

I have a list:

List<UserItem> userList = new ArrayList<>();

Where I add the following:

User father = new User();
father.setName("Peter");

UserItem parent = new UserItem(father, null);
userList.add(parent);

I then create another user:

User daughter = new User();
daughter.setName("Emma");

UserItem child = new UserItem(daughter, <OBJECT IN LIST WHERE NAME IS "PETER">);
userList.add(child);

However, I need to change the text wrapped in <> above to the parent object I added before (the father), specified by the name ("Peter" in this case).

How can I find an object in a List by a specific attribute? In my case, how can I find the object in the List that has the name "Peter"?

Please note that I add hundreds, sometimes thousands, of different users like this to the list. Each "parent" has a unique name.

Upvotes: 6

Views: 22441

Answers (3)

maydos
maydos

Reputation: 371

Answer to your question is here: https://stackoverflow.com/a/1385698/2068880

Stream peters = userList.stream().filter(p -> p.user.name.equals("Peter"))

However, as ruakh suggested, it's more reasonable to use Map<String, UserItem> to make it faster. Otherwise, it will iterate all the objects in the list to find users with name "Peter".

Upvotes: 3

Viet
Viet

Reputation: 3409

Other way with parallelStream with findAny

Optional<UserItem> optional = userList.parallelStream().findAny(p -> p.user.getName().equalsIgnoreCase("Peter"));
UserItem user = optional.isPresent() ? optional.get() : null; 

Upvotes: 2

Maroun
Maroun

Reputation: 95948

The obvious solution would be iterating on the list and when the condition is met, return the object:

for (User user : userList) {
    if ("peter".equals(user.getName()) {
        return user;
    }
}

And you can use filter (Java 8):

List<User> l = list.stream()
    .filter(s -> "peter".equals(s.getUser()))
    .collect(Collectors.toList());

to get a list with all "peter" users.

As suggested in comments, I think using Map is a better option here.

Upvotes: 11

Related Questions