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?
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!
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With