We would be looking at flatMap method in Java 8 streams and Optional. In our last tutorial we looked at map method in Java 8 stream example. Let us start with the examples
1. Flatten a List<List<String>> to List<String> using flatMap
Here we have two lists, a list of front-end languages and a list of back-end languages. And a wrapper list holds both of these lists. And we would like have the contents of both these lists in one single list.
1 2 3 4 5 6 7 8 9 10 |
public class ConvertListOfListOfStringsFlatMapExample { public static void main(String[] args) { List<List<String>> languageNames = Arrays.asList(Arrays.asList("Javascript", "HTML", "CSS"), Arrays.asList("Simula", "Java", "Python", "Ruby")); List<String> allLanguages = languageNames.stream().flatMap(each -> each.stream()).collect(Collectors.toList()); allLanguages.forEach(System.out::println); } } |
2. Flatten Map<String, List<String>> to List<String>
Here we have a list of languages grouped by a keyword like “frontend” and “backend”. So we would be flattening the map data to a list.
1 2 3 4 5 6 7 8 9 10 11 12 |
public class ConvertListMapStringFlatMapExample2 { public static void main(String[] args) { Map<String, List<String>> languageNames = new HashMap<>(); languageNames.put("frontend", Arrays.asList("Javascript", "HTML", "CSS")); languageNames.put("backend", Arrays.asList("Simula", "Java", "Python", "Ruby")); List<String> allLanguages = languageNames.values().stream().flatMap(each -> each.stream()) .collect(Collectors.toList()); allLanguages.forEach(System.out::println); } } |
3. Flatten Map<?, Map<?, List<String>>> to List<String>
Here we would be flattening a map of map. We would be using flatMap twice to flatten the data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class ConvertListMapOfMapStringFlatMapExample3 { private enum Gender { male, female } public static void main(String[] args) { Map<Integer, Map<Gender, List<String>>> allStudentsGorupedByAgeAndThenGender = new HashMap<>(); HashMap<Gender, List<String>> studentsGroupedByGender = new HashMap<>(); studentsGroupedByGender.put(Gender.male, Arrays.asList("Christian", "Barack", "Andrew")); studentsGroupedByGender.put(Gender.female, Arrays.asList("Andre", "Lorina", "Rakhi")); allStudentsGorupedByAgeAndThenGender.put(16, studentsGroupedByGender); // i want to get all the student names List<String> allLanguages = allStudentsGorupedByAgeAndThenGender.values().stream() .flatMap(each -> each.values().stream()).flatMap(each -> each.stream()).collect(Collectors.toList()); allLanguages.forEach(System.out::println); } } |
4. FlatMap in Optional
In Optional, flatMap can be used to process an intermediate result. Here are the Javadocs of flatMap in Optional.
If a value is present, apply the provided
Optional
-bearing mapping function to it, return that result, otherwise return an emptyOptional
.
Th Javadocs explain is pretty well, if a value is present, only then the mapping function is called. If the value is not present then the mapping funtion would not be invoked at all.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class FlatMapOptionalExample { public static void main(String[] args) { Optional<String> optional = Optional.of("Inbetween Result"); Optional<String> flatMap = optional.flatMap(s -> processTheOutput(s)); System.out.println(flatMap.get()); } private static Optional<String> processTheOutput(String s) { return Optional.of("Applied Transformation"); } } |
5. flatMapToInt
Let’s also see an example of flatMapToInt . In the below example we have a primitive int
type array. And we would like to have a sum of all the integers within the array. So we would use flatMapToInt to get IntStream and use the sum operation of IntStream
.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class FlatMaptoIntExample { public static void main(String[] args) { int[] integers = { 3, 2, 4, 10, 18 }; Stream<int[]> streamOfIntArray = Stream.of(integers); int sum = streamOfIntArray.flatMapToInt(x -> Arrays.stream(x)).sum(); System.out.println(sum); } } |
Summary
We looked at various types of data that we can flatten with the help of flatMap method provided by the Java 8 streams. I hope that you have also found them helpful. Please share in comments if you see any other interesting ways of using flatMap.
Could you give example for the case convert a list to list of list in java 8? Thanks
You can do this with a one liner. Here I am grouping them by smae string but different case.