Java 8 Stream 字符串排序列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39950785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 Stream sorting List of String
提问by saurabh suman
I am calling the sorted method on a stream. And the java doc says:
我正在调用流上的 sorted 方法。Java 文档说:
"Sorted method returns a stream consisting of the elements of this stream, sorted according to natural order."
“Sorted 方法返回一个由这个流的元素组成的流,按照自然顺序排序。”
But when I run the code below:
但是当我运行下面的代码时:
List<String> list = new ArrayList<String>();
list.add("b");
list.add("a");
list.add("z");
list.add("p");
list.stream().sorted();
System.out.println(list);
I am getting output as
我得到的输出为
[b, a, z, p]
Why am I not getting the output of a natural sort?
为什么我没有得到自然排序的输出?
回答by Elliott Frisch
Change this
改变这个
list.stream().sorted();
System.out.println(list);
to something like
像
list.stream().sorted().forEachOrdered(System.out::println);
Your method is println the list
(not the sorted stream). Alternatively (or additionally), you could shorten your initialization routine and re-collect the List
like
您的方法是 println list
(不是排序流)。或者(或另外),您可以缩短初始化程序并重新收集List
类似的
List<String> list = new ArrayList<>(Arrays.asList("b","a","z","p"));
list = list.stream().sorted().collect(Collectors.toList());
System.out.println(list);
Which outputs (as you probably expected)
哪些输出(如您所料)
[a, b, p, z]
回答by Elliott Frisch
Your stream has no terminal operator, and therefore is not processed. Terminal operators include but are not limited to: forEach, toArray, reduce, collect. Your code segment should be similar to
您的流没有终端运算符,因此不会被处理。终端操作符包括但不限于:forEach、toArray、reduce、collect。您的代码段应该类似于
list.stream().sorted().forEachOrdered(System.out::println);
回答by David Pham
If you want to have your sorted list.
如果你想有你的排序列表。
Let's change this
让我们改变这个
list.stream().sorted();
to
到
list.sort((e1, e2) -> e1.compareTo(e2));
Hope this help!
希望这有帮助!
回答by cringineer
You should collect the result of the sorting and then assign it to your list.
您应该收集排序的结果,然后将其分配到您的列表中。
List<String> list = new ArrayList<String>();
list.add("b");
list.add("a");
list.add("z");
list.add("p");
list = list.stream().sorted().collect(Collectors.toList());
System.out.println(list);