set元素上的flatMap

问题描述 投票:1回答:1

我有一个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是否有更好的方法?

java java-8 java-stream flatmap
1个回答
0
投票
您可以使用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

© www.soinside.com 2019 - 2024. All rights reserved.