Java8 streams: transpose a map with list values

I have a map with a key as String and a value as List. A list can have 10 unique values. I need to convert this map with the key as Integer and the value as List. An example as shown below:

Input:

Key 1: 1,2,3,4

Key 2: 2,3,4,5

Key 3: 3,4,5,1

Expected Result:

1: "Key-1", "Key-3"

2: "Key-1", "Key-2"

3: "Key-1", "Key-2", "Key-3"

4: "Key-1", "Key-2", "Key-3"

5: Key-2, Key-3

I know that using for loops I can achieve this, but I needed to know that this can be done via streams / lamda in java8.

-Thank.

+4
4

, , :

import java.util.AbstractMap.SimpleEntry;

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;

...

Map<Integer, List<String>> transposeMap =
    map.entrySet()
       .stream()
       .flatMap(e -> e.getValue().stream().map(i -> new SimpleEntry<>(i, e.getKey())))
       .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
+11

Alexis , flatMap . , , groupingBy :

Map<Integer, List<String>> mapT = map.entrySet().stream().collect(
    HashMap::new,
    (m,e) -> e.getValue().forEach(
                 i -> m.computeIfAbsent(i,x -> new ArrayList<>()).add(e.getKey())),
    (m1,m2) -> m2.forEach((k,v) -> m1.merge(k, v, (l1,l2)->{l1.addAll(l2); return l1;})));
+4

( , ), :

Map<Integer, List<String>> transposeMap = new HashMap<>();

map.forEach((key, list) -> list.stream().forEach(
    elm -> transposeMap.put(elm,
        transposeMap.get(elm) == null ? Arrays.asList(key) : (Stream.concat(transposeMap.get(elm).stream(),
            Arrays.asList(key).stream()).collect(Collectors.toList())))));

, Map<String, List<Integer>> map - , . transposeMap , .

+2

, Person .

Map<SEX,List<Person>> 

Map<SEX,List<Person>> map =  personList.stream()

                           .collect(Collectors.groupingBy(Person::getGender));

- ( )

key:MALE
age31sexMALE
age28sexMALE

key:FEMALE
age40sexFEMALE
age44sexFEMALE
+1

Source: https://habr.com/ru/post/1648448/


All Articles