Java 8 Sort Stream String List

I call the sorted method in the stream. And the java document says:

"The sorted method returns a stream consisting of the elements of this stream, sorted according to the 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 get output as

 [b, a, z, p] 

Why am I not getting a natural looking conclusion?

+5
source share
4 answers

Change it

 list.stream().sorted(); System.out.println(list); 

to something like

 list.stream().sorted().forEachOrdered(System.out::println); 

Your println list method (not a sorted stream). Alternatively (or additionally), you can shorten your initialization procedure and reassemble the list as

 List<String> list = new ArrayList<>(Arrays.asList("b","a","z","p")); list = list.stream().sorted().collect(Collectors.toList()); System.out.println(list); 

What are the outputs (as you expected)

 [a, b, p, z] 
+7
source

There is no terminal operator in your stream and therefore it is not processed. Terminal operators include, but are not limited to: forEach, toArray, reduce, assemble. Your code segment should look like

 list.stream().sorted().forEachOrdered(System.out::println); 
+3
source

You must collect the sort result 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); 
+2
source

If you want to have a sorted list.

Change it

 list.stream().sorted(); 

to

 list.sort((e1, e2) -> e1.compareTo(e2)); 

Hope this help!

0
source

Source: https://habr.com/ru/post/1257942/


All Articles