Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream sorting List of String [duplicate]

I am calling the sorted method on a stream. And the java doc says:

"Sorted method returns a stream consisting of the elements of this stream, sorted according to natural order."

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?

like image 582
saurabh suman Avatar asked Oct 10 '16 03:10

saurabh suman


2 Answers

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!

like image 117
David Pham Avatar answered Oct 13 '22 04:10

David Pham


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

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]
like image 27
Elliott Frisch Avatar answered Oct 13 '22 05:10

Elliott Frisch