Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting behaving differently?

Tags:

java

java-8

When I try to sort a string array/list using Comparator.naturalOrder() it does not respect the natural order of list. Here's the snippet I used :

List< String > ordered = Arrays.asList( "This", "is", "the", "natural" ,"order");

System.out.println( "Natural order" );

ordered.forEach( System.out::println );

ordered.sort(Comparator.naturalOrder( ));

System.out.println( "After ordering" );

for ( String string: ordered ) {
    System.out.println( string );
}

Output:

Natural order
This
is
the
natural
order

After ordering
This
is
natural
order
the

Why is Comparator.naturalOrder() behaving such way? Same is the case when I try Comparator.reverseOrder().

like image 389
stackFan Avatar asked Apr 08 '26 20:04

stackFan


1 Answers

naturalOrder means according to Comparator or plain String comparison order, not source's encounter order. These are totally different things.

May be a Stream of Integer would be easier to understand:

Stream.of(3,4,1,2)...

encounter order is 3, 4, 1, 2

sorted order is 1, 2, 3, 4 - meaning naturally sorted (via Comparator.naturalOrder())

like image 65
Eugene Avatar answered Apr 11 '26 08:04

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!