Find specific object in a List by attribute

后端 未结 3 1302
日久生厌
日久生厌 2020-12-20 21:54

I have a list:

List userList = new ArrayList<>();

Where I add the following:

User father = new User()         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-20 22:06

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

提交回复
热议问题