Nested lists with streams in Java8
You can do it with flatMap
.
I made an example with Company
which contains a list of Person
:
public static void main(String[] args) {
List<Company> companies = Arrays.asList(
new Company(Arrays.asList(new Person("Jon Skeet"), new Person("Linus Torvalds"))),
new Company(Arrays.asList(new Person("Dennis Ritchie"), new Person("Bjarne Stroustrup"))),
new Company(Arrays.asList(new Person("James Gosling"), new Person("Patrick Naughton")))
);
List<String> persons = companies.stream()
.flatMap(company -> company.getPersons().stream())
.map(Person::getName)
.collect(Collectors.toList());
System.out.println(persons);
}
Output :
[Jon Skeet, Linus Torvalds, Dennis Ritchie, Bjarne Stroustrup, James Gosling, Patrick Naughton]
You can use two flatMap
then a filter
then you can pick the first one or if no result return null
:
C c1 = listOfAObjects.stream()
.flatMap(a -> a.getList().stream())
.flatMap(b -> b.getPr().stream())
.filter(c -> c.getName().equalsIgnoreCase(name))
.findFirst()
.orElse(null);
listOfObjectsA.stream()
.flatMap(a -> a.getListOfObjectsB.stream())
.flatMap(b -> b.getListOfObjectsC().stream())
.filter(c -> name.equals(c.getName()))
.findAny()
.orElse(....)