Vipul Pandey
Vipul Pandey

Reputation: 1738

How to match an element to an object's list and return the object

I have an object model similar to this:

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
}

Now I need to find the user of which the id of the address is predefined, let's say 4, from the userList from the Java Stream API.

Upvotes: 0

Views: 120

Answers (1)

Eugene
Eugene

Reputation: 120848

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

Upvotes: 1

Related Questions