我有一个Map<String, Set<String>>
,假设它是
{"a": {"a1", "a2", "a3"}, "b": {"b1", "b2", "b3"}, "c": {"c1", "c2"}, "d": {}}
我有一个映射键集流,我想将流集的每个元素平面映射到映射中相应值集的元素,例如
输入流:
{"a","b"}
{"a","c"}
{"b","c","d"}
输出流:
//first set
{"a1","b1"}
{"a1","b2"}
{"a1","b3"}
{"a2","b1"}
{"a2","b2"}
{"a2","b3"}
{"a3","b1"}
{"a3","b2"}
{"a3","b3"}
//second set
{"a1","c1"}
{"a1","c2"}
{"a2","c1"}
{"a2","c2"}
{"a3","c1"}
{"a3","c2"}
//third set would be flatmapped to nothing, as "d" is mapped to an empty set
如何使用 Java8 流来做到这一点?
是否有更好的方法仅使用 Java SE 8 API 来完成此操作?
最佳答案
您可以使用 Apache Commons Collections
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
示例:
public class App {
public static void main(String[] args) {
// With an ArrayList for the values
MultiValuedMap<String, String> map1 = new ArrayListValuedHashMap<>();
map1.put("a", "a1");
map1.put("a", "a2");
map1.put("a", "a3");
map1.put("a", "a4");
map1.put("a", "a5");
map1.put("b", "b1");
map1.put("b", "b1");
map1.put("b", "b3");
map1.put("b", "b4");
map1.put("b", "b5");
map1.entries().forEach(e -> System.out.println(e.getKey() + " - " + e.getValue()));
System.out.println("----");
// With a HashSet for the values
MultiValuedMap<String, String> map2 = new HashSetValuedHashMap<>(map1);
map2.entries().forEach(e -> System.out.println(e.getKey() + " - " + e.getValue()));
}
}
输出如下所示:
a - a1
a - a2
a - a3
a - a4
a - a5
b - b1
b - b1
b - b3
b - b4
b - b5
----
a - a1
a - a2
a - a3
a - a4
a - a5
b - b3
b - b4
b - b5
b - b1
关于java - 集合元素上的 flatMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58349058/