从 Map<K,Collection<V>> 创建 Multimap,键为 V[0],值为 K 使用 Java 8

Create Multimap from Map<K,Collection<V>> with key as V[0] and value as K using Java 8

我有一个 Map<String,List<String>>(例如 inputMap),我想将其转换为另一个 Map<String,List<String>>,其中新地图中的每个 (k,v) 是 (v.get(0 ),k) 的 inputMap.

例如

X -> B,C,D
Y -> B,D,E
Z -> B,G,H
P -> A,B,D
Q -> A,D,F
R -> A,C,B

B->X,Y,Z
A->P,Q,R

我最初认为我可以使用类似

的东西来做到这一点
inputMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue.get(0),Map.Entry::getKey));

然后把这个map转成multimap,但是我写不出来Map.Entry::getValue.get(0)

如果我可以在 .collect() 本身中创建多图,那就太好了。

这是一种方法:

Map<String, List<String>> output = input.entrySet().stream()
        //create new entries mapping B to X, B to Y, B to Z etc.
        .map(e -> new SimpleEntry<>(e.getValue().get(0), e.getKey()))
        //we group by the key (B or A) and we collect the values into a list
        .collect(groupingBy(Entry::getKey, mapping(Entry::getValue, toList())));

方法引用不是那样工作的。如果您不能将函数表达为对 单个 方法的引用,则需要一个 lambda 表达式。

此外,当您需要多个值时,toMap 收集器不是最佳选择,groupingBy 是合适的工具。

Map<String,List<String>> result=map.entrySet().stream().collect(
    Collectors.groupingBy(e->e.getValue().get(0),
        Collectors.mapping(Map.Entry::getKey, Collectors.toList())));

可以直接收藏成Multimap:

Multimap<String, String> result = inputMap.entrySet().stream()
        .collect(
                ArrayListMultimap::create,
                (mm,e) -> mm.put(e.getValue().get(0), e.getKey()),
                Multimap::putAll
        );