给定列表列表的唯一元素列表

List of unique elements, given a List of Lists

给定一个 ArrayList transactions 排序的整数 ArrayLists,我正在编写代码 return 它的独特元素。例如,给定

transactions = [
  [1, 1, 2, 3, 5, 8, 13, 21],
  [2, 3, 6, 10],
  [11, 21]
]

我的代码应该 return 唯一元素,保留排序顺序:

[1, 2, 3, 5, 6, 8, 10, 11, 13, 21]

为此,我只是将每个列表中的每个元素添加到 LinkedHashSet,根据其定义,它会保持排序并删除重复项。

Set<Integer> uniqEl = new LinkedHashSet<>();

for (List<Integer> l : transactions) {
    for (Integer n : l) {
        uniqEl.add(n);
    }
}

尽管我的代码通过利用 Java 库完成了工作,但我想要更高效的实现。有没有关于更好的算法从列表列表中生成排序的唯一元素列表的想法?

如果 "more efficient",你的意思是更精简,那么这种功能性方法可能会为你解决问题:

List<Integer> list =
transactions.stream()
            .flatMap(List::stream)
            .distinct()
            .sorted()
            .collect(Collectors.toList());

没有比使用 TreeSet 并将所有列表添加到该集合中更有效的方法了。 TreeSet 将按元素的自然顺序升序对元素进行排序,并且忽略重复元素。

public static void main(String[] args) {
    List<List<Integer>> transactions = Arrays.asList(Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21), Arrays.asList(2, 3, 6, 10), Arrays.asList(11, 21));

    SortedSet<Integer> set = new TreeSet<>();
    for (List<Integer> l : transactions) {
        set.addAll(l);
    }
}

当然,您可以使用 Java 8 个流来一行:

SortedSet<Integer> set = transactions.stream()
                                     .flatMap(List::stream)
                                     .collect(Collectors.toCollection(TreeSet::new));

使用此解决方案,您可以 运行 并行执行它,但您必须衡量它是否提高了性能。

对于 Eclipse Collections,以下应该有效:

MutableList<MutableList<Integer>> transactions =
    Lists.mutable.with(
        Lists.mutable.with(1, 1, 2, 3, 5, 8, 13, 21), 
        Lists.mutable.with(2, 3, 6, 10), 
        Lists.mutable.with(11, 21));
SortedSet<Integer> flattenedDistinct =
    transactions.asLazy().flatCollect(l -> l).toSortedSet();

Assert.assertEquals(
    SortedSets.mutable.of(1, 2, 3, 5, 6, 8, 10, 11, 13, 21), flattenedDistinct);

您还可以通过将 flatCollect 的 eager 版本与目标集合一起使用来实现相同的结果,如下所示:

SortedSet<Integer> flattenedDistinct =
    transactions.flatCollect(l -> l, SortedSets.mutable.empty());

为避免对整数进行装箱,您可以使用 Eclipse Collections 中可用的原始集合。

MutableList<MutableIntList> transactions = Lists.mutable.with(
    IntLists.mutable.with(1, 1, 2, 3, 5, 8, 13, 21),
    IntLists.mutable.with(2, 3, 6, 10), 
    IntLists.mutable.with(11, 21));
MutableIntList flattenedDistinct =
    transactions.injectInto(IntSets.mutable.empty(), MutableIntSet::withAll).toSortedList();

Assert.assertEquals(
    IntLists.mutable.with(1, 2, 3, 5, 6, 8, 10, 11, 13, 21), flattenedDistinct);

注意:我是 Eclipse Collections 的贡献者。