Reputation: 894
I have List of Person objects
public class Person {
private String name;
private List<Animal> animals;
}
Which have list of animal objects:
public class Animal {
private String name;
}
I am trying to create a new list out of it and I am trying to extract only those Person who have a specific name
List<Person> filteredPeople = people.stream()
.filter(e -> e.getName().equals("John")).collect(Collectors.toList());
Is it possible to add one more filter and how do I access the Animal list inside the person so I can filter by the animal name - for example if any the Animals(inside Person) name is "Lucky" to also put this Person object inside the new list?
Looks like this is not a valid idea:
.filter(e -> e.getAnimals().stream().filter(f -> f.getName().equals("lucky")))
Upvotes: 0
Views: 613
Reputation: 76
You can achieve this by
persons.stream()
.filter(p -> p.getName.equals("John") || p.getAnimals().stream().anyMatch(a -> a.getName.equals("lucky")))
.collect(Collectors.toList())
Upvotes: 1