Seb*_*ino 2 java sorting collections java-stream
我曾经使用以下行来在Java中出现流之前对元素进行排序:
Collections.sort(collection, new CustomComparator());
Run Code Online (Sandbox Code Playgroud)
现在我发现我可以通过以下方式获得相同的结果:
collection.stream().sorted(new CustomComparator());
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,我都使用一个列表和一个实现的自定义比较器Comparator(我需要这个并且不能在类本身上实现它).
我没有找到任何表明它们在任何方面都不同的东西,除了流解决方案看起来更好的事实.
使用流版本有什么好处吗?我的意思是......性能更高吗?有什么区别吗?
collection.stream().sorted(new CustomComparator())不排序collection,只对流进行排序.
要使用Stream API获得类似的结果,您应该使用终端操作 - 收集到一个新列表:
collection.stream().sorted(new CustomComparator()).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
它不会修改原始集合(流源),但Collections.sort会.
如果原始订单很重要,我会复制该集合并对其进行排序.
List<?> collectionCopy = new ArrayList(collection);
Collections.sort(collectionCopy, new CustomComparator());
Run Code Online (Sandbox Code Playgroud)