Java 8转换Map< K,List< V>>映射< V,列表< K>> [英] Java 8 convert Map<K, List<V>> to Map<V, List<K>>

查看:315
本文介绍了Java 8转换Map< K,List< V>>映射< V,列表< K>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将地图< K,列表< V>> 转换为地图< V,列表< K>>
我一直在努力解决这个问题。

I need to convert Map<K, List<V>> to Map<V, List<K>>. I've been struggling with this issue for some time.

很明显如何进行转换 Map< K,V> 地图< V,列表< K>>

It's obvious how to do conversion Map<K, V> to Map<V, List<K>>:

.collect(Collectors.groupingBy(
     Map.Entry::getKey, 
     Collectors.mapping(Map.Entry::getValue, toList())
)

但我找不到解决初始问题。是否有一些易于准备的java-8方式这样做?

But I can't find solve an initial issue. Is there some easy-to-ready-java-8 way to do it?

推荐答案

我认为你很接近,你需要 flatMap 那些 Stream 的条目并从那里收集。我已经使用了现在的 SimpleEntry ,但是你可以使用某种 Pair

I think you were close, you would need to flatMap those entries to a Stream and collect from there. I've used the already present SimpleEntry, but you can use a Pair of some kind too.

initialMap.entrySet()
          .stream()
          .flatMap(entry -> entry.getValue().stream().map(v -> new SimpleEntry<>(entry.getKey(), v)))
          .collect(Collectors.groupingBy(
               Entry::getValue,
               Collectors.mapping(Entry::getKey, Collectors.toList())
         ));

好吧,如果你不想创造那些的额外开销SimpleEntry 实例,你可以做的有点不同:

Well, if you don't want to create the extra overhead of those SimpleEntry instances, you could do it a bit different:

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

    initialMap.forEach((key, values) -> {
        values.forEach(value -> result.computeIfAbsent(value, x -> new ArrayList<>()).add(key));
    });

这篇关于Java 8转换Map&lt; K,List&lt; V&gt;&gt;映射&lt; V,列表&lt; K&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆