给定排序整数ArrayList transactions的ArrayLists,我正在编写代码以返回其唯一元素。例如,给定
transactions = [
[1, 1, 2, 3, 5, 8, 13, 21],
[2, 3, 6, 10],
[11, 21]
]我的代码应该返回唯一的元素,保持排序顺序:
[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库完成了任务,但我希望有一个更高效的实现。有什么更好的算法来从列表列表中生成一个排序的唯一元素列表吗?
发布于 2016-02-15 17:17:25
您将无法获得比使用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));使用此解决方案,您可以并行运行它,但您必须度量它是否提高了性能。
发布于 2016-02-15 17:14:38
如果说“更有效率”,你指的是更精简,那么这种功能方法可能对你有好处:
List<Integer> list =
transactions.stream()
.flatMap(List::stream)
.distinct()
.sorted()
.collect(Collectors.toList());发布于 2016-03-23 15:43:34
对于日食收藏,以下内容应该可以工作:
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的热切版本和目标集合实现相同的结果,如下所示:
SortedSet<Integer> flattenedDistinct =
transactions.flatCollect(l -> l, SortedSets.mutable.empty());为了避免ints的装箱,您可以使用Eclipse集合中可用的原始集合。
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集合的贡献者。
https://stackoverflow.com/questions/35415134
复制相似问题