[英]How to create a reverse map when original map contains collection as the value?
Let's say my original Map
contains the following: 假设我的原始
Map
包含以下内容:
Map<String, Set<String>> original = Maps.newHashMap();
original.put("Scott", Sets.newHashSet("Apple", "Pear", "Banana");
original.put("Jack", Sets.newHashSet("Banana", "Apple", "Orange");
And I want to create a reversed Map
containing the following: 我想创建一个包含以下内容的反向
Map
:
"Apple": ["Scott", "Jack"]
"Pear": ["Scott"]
"Banana": ["Scott", "Jack"]
"Orange": ["Jack"]
I know it can be done in old fashion (pre-Java 8), but how do I achieve the same using Java Stream API? 我知道它可以用旧方式(Java 8之前的版本)完成,但是如何使用Java Stream API实现相同的功能呢?
Map<String, Set<String>> reversed = original.entrySet().stream().map(x -> ????).collect(??)
There's similar question posted here , but that only works for single valued Map
s. 有张贴类似的问题在这里 ,但只适用于单值
Map
秒。
You can break the Map
into key-value pairs (where each key and value is a single String
) by using flatMap
, and then collect them as you wish: 您可以使用
flatMap
将Map
拆分为键值对(其中每个键和值都是单个String
),然后根据需要收集它们:
Map<String,Set<String>> rev =
original.entrySet ()
.stream ()
.flatMap (e -> e.getValue ()
.stream ()
.map (v -> new SimpleEntry<String,String>(v,e.getKey ())))
.collect(Collectors.groupingBy (Map.Entry::getKey,
Collectors.mapping (Map.Entry::getValue,
Collectors.toSet())));
System.out.println (rev);
Output: 输出:
{Apple=[Jack, Scott], Pear=[Scott], Orange=[Jack], Banana=[Jack, Scott]}
A more imperative but simpler solution would be using forEach
: 更迫切但更简单的解决方案是使用
forEach
:
Map<String, Set<String>> original,result; // initialised
original.forEach((key, value) -> value.forEach(v ->
result.computeIfAbsent(v, k -> new HashSet<>()).add(key)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.