如何将元素与对象列表匹配并返回对象

时间:2018-07-24 12:08:47

标签: java list java-8 java-stream

我有一个与此相似的对象模型:

List<User> userList; //and each user contains list of address
List<Address>; 

class User {

    private Long id;
    List<Address> address;

    // getters & setters
} 

class Address {

    Long id
}

现在,我需要从Java Stream API的4中找到预定义地址ID的用户,例如userList

1 个答案:

答案 0 :(得分:1)

 Optional<User> user = userList.stream()
         .filter(x -> x.getAddress().stream().anyMatch(a -> a.getId() == 4))
         .findAny();