How can I go from a map of integers to lists of strings such as:
<1, ["a", "b"]>,
<2, ["a", "b"]>
To a flattened list of strings such as:
["1-a", "1-b", "2-a", "2-b"]
in Java 8?
The standard solution is to use the Stream. flatMap() method to flatten a List of Lists. The flatMap() method applies the specified mapping function to each element of the stream and flattens it.
Using Collectors. toMap() method: This method includes creation of a list of the student objects, and uses Collectors. toMap() to convert it into a Map.
Here is the simple, concise code to perform the task. // listOfLists is a List<List<Object>>. List<Object> result = new ArrayList<>(); listOfLists. forEach(result::addAll);
You can use flatMap
on values as:
map.values()
.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
Or if you were to make use of the map entries, you can use the code as Holger pointed out :
map.entries()
.stream()
.flatMap(e -> e.getValue().stream().map(s -> e.getKey() + s))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With