【问题标题】:flatMap on elements of a setflatMap 在集合的元素上
【发布时间】:2020-02-09 10:36:44
【问题描述】:

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

【问题讨论】:

  • 没有。你想要所有的组合。流与元素一起工作,一次一个。您不能组合流中其他地方的元素。
  • 是的,正如@Bohemian Streams 所说的那样,一次可以使用元素,你想要它的所有组合,所以你不能使用流
  • 比什么更好的方法?你的尝试是什么样的?

标签: java java-8 java-stream flatmap


【解决方案1】:

您可以使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    相关资源
    最近更新 更多