When working with Stream in Java, sometime we can have a Stream with datatype of a List, Set or Array of object. For example:
1 2 3 4 5 6 7 8 9 10 |
List<String> students1 = new ArrayList<>(); students1.add("Khanh"); List<String> students2 = new ArrayList<>(); students2.add("Thanh"); students2.add("Dung"); List<List<String>> students = Arrays.asList(students1, students2); Stream<List<String>> stream = students.stream(); |
Here, we have List of List of String object and when convert into Stream object, we have Stream of List of String object.
When that, if we want to manipulate on this Stream object like filter, then we cannot do that. For example:
To resolve this problem, we can use flatMap() method before the manipulation you need. With flatMap() method, we can flatten our Stream of List, Set or Array object into a simple one like Stream of object. For example:
1 2 3 4 5 6 7 8 9 10 11 |
List<String> students1 = new ArrayList<>(); students1.add("Khanh"); List<String> students2 = new ArrayList<>(); students2.add("Thanh"); students2.add("Dung"); List<List<String>> students = Arrays.asList(students1, students2); Stream<List<String>> stream = students.stream(); Stream<String> flatMap = stream.flatMap(l -> l.stream()); |
Now, we can use flatMap() method to resolve our problem.