java - 集合元素上的 flatMap

标签 java java-8 java-stream flatmap

我有一个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/

相关文章:

java - OpenSuse 13.2 上的 Qt for Android

java - 用于 Elasticsearch 的RestClient

java - 麻烦样式 ScrollPane Angular 颜色

java - 我应该将 java Stream.map 函数与 switch 语句一起使用吗?

java - BufferedReader 出现意外的 java.util.NoSuchElementException

java - 不同对象的哈希码相同

java - 使用 java 中的进程构建器在 linux 上执行海关命令

java - collectingAndThen方法足够高效吗?

java - 如何一起使用 completablefuture 和 Streams

java - 使用 collect() 在流中加入 "parallel"列表