Java 8 转换 Map<K, List<V>>到地图<V,列表<K>>

2022-01-22 00:00:00 mapping collections java-8 java java-stream

我需要将 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.

MapMap的转换很明显:

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

相关文章