In Java 8 Stream API,
flatMap() method is an intermediate functions for streams, in that, it will produce a final result but used to apply transformations on the elements of a Stream. It is possible to to chain multiple
flatMap() while processing a single stream.
Both
map() and
flatMap() both can be applied to a Stream<T> and return a Stream<R> or transformed elements, but the main difference is that
map() produces one output element for each input element, whereas
flatMap() produces any number (0-n) of output elements for each input element. Put simply, when using a
map(), the resulting stream would have same number or elements as the input stream, where as it can be different in case of a
flatMap(). The following example illustrates the differences the use of
flatMap()
flatMap() with Lists and Sets
flatMap() can be used to convert List<List<T>> to List<T> or Set<Set<T>> to Set<T>. Here we see an example which applies
flatMap() on List<List<String>> to result in List<String>.
List<List<String>> input = Arrays.asList(Arrays.asList("T", "h", "i", "s"), Arrays.asList("i", "s"),
Arrays.asList("J", "a", "v", "a", "8"), Arrays.asList("S", "t", "r", "e", "a", "m"),
Arrays.asList("f", "l", "a", "t", "M", "a", "p", "(", ")"),
Arrays.asList("E", "x", "a", "m", "p", "l", "e"));
input.stream().flatMap(list -> list.stream()).forEach(System.out::println);
flatMap() with Arrays
Integer[][] pie = {{3,1},{4,1},{5,6}};
Arrays.stream(pie).flatMap(num < Arrays.stream(num)).
forEach(System.out::println);
Print Words in a text file using flatMap()
Here we see a way to read lines from a text file using Files.Lines() method to get a Stream of lines and apply
flatMap() to split the words in the line and print.
Files.lines(Paths.get("C:/test/test.txt")).flatMap(x->Arrays.stream(x.split(" "))).forEach(System.out::println);
Here is the full file with all three examples
package streams;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class StreamFlatMapTest {
public static void main(String[] args) {
List<List<String>> input = Arrays.asList(Arrays.asList("T", "h", "i", "s"), Arrays.asList("i", "s"),
Arrays.asList("J", "a", "v", "a", "8"), Arrays.asList("S", "t", "r", "e", "a", "m"),
Arrays.asList("f", "l", "a", "t", "M", "a", "p", "(", ")"),
Arrays.asList("E", "x", "a", "m", "p", "l", "e"));
input.stream().flatMap(list -> list.stream()).forEach(System.out::println);
Integer[][] pie = {{3,1},{4,1},{5,6}};
Arrays.stream(pie).flatMap(num -> Arrays.stream(num)).
forEach(System.out::println);
try {
Files.lines(Paths.get("C:/test/test.txt")).flatMap(x->Arrays.stream(x.split(" "))).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment