6

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.

user5725851
  • 69
  • 1
  • 1
  • 3
  • 3
    Are you sure you want a 'List'? It's certainly possible to iterate over a list to get the specific element you want, but that's not really the best way to use them. It sounds like you want a `Map`. – ruakh Dec 29 '15 at 07:15
  • I agree with ruakh. To answer the question though: you need to loop over the list, and find the user that has "Peter" as its name. Surely you've done that before, in your first algorithm course. – JB Nizet Dec 29 '15 at 07:20

3 Answers3

11

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.

Maroun
  • 94,125
  • 30
  • 188
  • 241
3

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

Community
  • 1
  • 1
maydos
  • 331
  • 2
  • 5
2

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; 
Viet
  • 3,349
  • 1
  • 16
  • 35