Situation:
You have a list of lists, and you need to merge them into a single list.
Solution:
List<List<String>> listOfLists = Arrays.asList(Arrays.asList("a", "b"), Arrays.asList("c", "d"));
List<String> flattenedList = listOfLists.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flattenedList);
Explanation:
The flatMap
method is used to convert the list of lists into a single stream, which is then collected into a list.
Result:
[a, b, c, d]
Leave a Reply