Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a list inside a map in Java 8

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?

like image 404
Rodrigo Avatar asked Apr 04 '19 15:04

Rodrigo


People also ask

How do I flatten a list 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.

Can we convert list to map in Java?

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.

How can I turn a list of lists into a list in Java 8?

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);


1 Answers

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());
like image 143
Naman Avatar answered Oct 16 '22 12:10

Naman