从一组集合中添加所有项目的最佳方法

Best way to addAll items from a Collection of Sets

实现以下目标的最佳、成本最低、性能最好的方法是什么:

我确实有一个 Collection 对象 myObject,它提供了一个返回一组整数的方法。我想将集合中的所有项目添加到一个新集合中。

LinkedList<myObject>  ll = new LinkedList<>();

    //fill the list bla bla

Set<Integer> result = ll.stream()
    .map(f -> f.getTheSet())
    .flatMap(Set::stream)
    .collect(Collectors.toCollection(TreeSet::new));

System.out.println(result.toString());

是否有更好的方法从所有对象中获取包含所有整数的结果集? 我想用 flatMap 命令避免 "unpacking the set"。相反,我考虑像 .addAll 之类的东西,或者它最终无关紧要,因为 .addAll 无论如何都会解压?

您可以使用 addAll3-argument collect 进行收集:

Set<Integer> result = ll.stream()
        .map(MyObject::getTheSet)
        .collect(HashSet::new, Set::addAll, Set::addAll);

HashSet::new 创建一个新容器,Set::addAll 将每个集合添加到容器中,第二个 Set::addAll 合并两个容器,如果这个流是 运行 并行的。

(如果您特别想要 TreeSet,则使用 TreeSet::new

Instead i think about something like .addAll or does it in the end not matter, because .addAll unpacks anyway?

TreeSet.addAll() 有一个优化的代码路径,用于添加实现 SortedSet 的集合,假设它们具有相同的排序顺序。

警告:这是一个未记录的实施细节,因此可能会发生变化。

您自己可以很容易地找到这些信息,只需查看 JDK 源代码,即 included in the src.zip shipped with the JDK