stackFan
stackFan

Reputation: 1608

Sorting behaving differently?

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

Upvotes: 3

Views: 143

Answers (2)

anvita surapaneni
anvita surapaneni

Reputation: 369

naturalOrder() returns a Comparator that compares Comparable objects in natural order.

In your example, it is comparing the entries of the collection in dictionary order. (using the ASCII value for each letter).

Upvotes: 1

Eugene
Eugene

Reputation: 120848

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

Upvotes: 6

Related Questions