Skip to content

Instantly share code, notes, and snippets.

@adityachaudhari
Created October 17, 2021 11:51
Show Gist options
  • Save adityachaudhari/6482e1df76990726e43c6f26e449fbf3 to your computer and use it in GitHub Desktop.
Save adityachaudhari/6482e1df76990726e43c6f26e449fbf3 to your computer and use it in GitHub Desktop.
Understand difference between map and flatmap
package com.java8.streams;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MapAndFlapMapUnderstanding {
public static void main(String[] args) {
System.out.println("Map example : \nTake string list and return list of integers having size of strings respectively");
List<String> listOfString = Arrays.asList("Str1", "String22", "RandomString", "AanotherRandomString");
List<Integer> charactersInStringList = listOfString.stream().map(string -> string.length()).collect(Collectors.toList());
charactersInStringList.forEach(element -> System.out.print(element + " "));
System.out.println("\nFlatMap : convert list of list of integers into single list of integers");
List<List<Integer>> listOfListOfIntegers = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6));
System.out.println("list of list of integers before flattening" + listOfListOfIntegers);
List<Integer> listInteger = listOfListOfIntegers.stream().flatMap(list -> list.stream()).collect(Collectors.toList());
System.out.println("list of list of integers after flattening" + listInteger);
}
}
Output :
Map example :
take string list and return list of integers having size of strings respectively
4 8 12 20
FlatMap : convert list of list of integers into single list of integers
list of list of integers before flattening[[1, 2], [3, 4], [5, 6]]
list of list of integers after flattening[1, 2, 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment