Sorting behaving differently?

stackFan :

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().

Eugene :

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())

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87154&siteId=1