As suggested in the comments, here a full example showing how to flatten out a stream of streams to a stream of an object (known as Stream concatenation):
The title should be edited to "Merge Streams" or "Concatenate lists"
public class Community {
private List<Person> persons;
// Constructors, getters and setters
}
--
public class Person {
private List<Address> addresses;
// Constructors, getters and setters
}
--
public class Address {
private String city;
// Constructors, getters and setters
@Override
public String toString() {
return "Address{" +
"city='" + city + '\'' +
'}';
}
}
Demo:
public class AggregationDemo {
public static void main(String[] args) {
List<Community> communities = List.of(
new Community(List.of(new Person(List.of(new Address("Paris"))))),
new Community(List.of(new Person(List.of(new Address("Florence"))))));
List<Address> addresses = communities.stream()
.flatMap(community -> community.getPersons().stream())
.flatMap(person -> person.getAddresses().stream())
.collect(Collectors.toList());
List<List<Person>> collectedListOfList = communities.stream()
.map(community -> community.getPersons())
.collect(Collectors.toList());
addresses.forEach(System.out::println);
collectedListOfList.forEach(System.out::println);
}
}
Output:
Person{addresses=[Address{city='Paris'}]}
Person{addresses=[Address{city='Florence'}]}
[Person{addresses=[Address{city='Paris'}]}]
[Person{addresses=[Address{city='Florence'}]}]