In the below example we have list of List which we need to combine in single list.
The flatMap() operation has the effect of applying a one-to-many transformation to the elements of the stream,
and then flattening the resulting elements into a new stream.
packagecom.examples;importjava.util.Arrays;importjava.util.List;importjava.util.Set;importjava.util.stream.Collectors;publicclassApp{publicstaticvoidmain(String[]args){List<Employee>employees=Arrays.asList(newEmployee(1,"Harish",Arrays.asList("Cricket","Music","Books")),newEmployee(2,"Tim",Arrays.asList("Football","Dancing","Books")),newEmployee(3,"Mary",Arrays.asList("Chess","Music","Gardening")));Set<String>hobbies=employees.stream().map(emp->emp.getHobbies())// this is list of hobbies
.flatMap(hobby->hobby.stream())// hobby stream
.collect(Collectors.toSet());System.out.println(hobbies);//[Chess, Cricket, Music, Gardening, Dancing, Books, Football]
}}classEmployee{privateintempId;privateStringempName;privateList<String>hobbies;publicEmployee(intempId,StringempName,List<String>hobbies){this.empId=empId;this.empName=empName;this.hobbies=hobbies;}publicintgetEmpId(){returnempId;}publicvoidsetEmpId(intempId){this.empId=empId;}publicStringgetEmpName(){returnempName;}publicvoidsetEmpName(StringempName){this.empName=empName;}publicList<String>getHobbies(){returnhobbies;}publicvoidsetHobbies(List<String>hobbies){this.hobbies=hobbies;}@OverridepublicStringtoString(){return"Employee{"+"empId="+empId+", empName='"+empName+'\''+", hobbies="+hobbies+'}';}}
Conclusion
I hope this clarifies how to merge streams in Java using Stream API.