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

问题描述

我需要将 Map> 转换为 Map.我一直在为这个问题苦苦挣扎.

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

Map到Map的转换很明显:

.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?

推荐答案

我认为你很接近,你需要将这些条目 flatMapStream 并从那里.我使用了已经存在的 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;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-18 13:23