Thursday, July 22, 2021

map() method vs flatMap() method

map() method is for data transformation

flatMap() method is data transformation and flattening the final output

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.

flatMap() is an intermediate operation.

map() method is for one to one mapping.

flatMap() method is for one to many mapping.

Example of map() method, convert lowercase characters into uppercase

List<Character> letters = Arrays.asList('a','b','c','d');

List<Character> upperCaseLetters = letters.stream().map(x>Character.toUpperCase(x)).collect(Collectors.toList());

System.out.println(upperCaseLetters);


Source - https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html


No comments:

Post a Comment