有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java排序行为不同?

当我尝试使用Comparator.naturalOrder()对字符串数组/列表进行排序时,它不遵守列表的自然顺序。以下是我使用的代码片段:

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 );
}

输出:

Natural order
This
is
the
natural
order

After ordering
This
is
natural
order
the

为什么Comparator.naturalOrder()的行为如此?我尝试Comparator.reverseOrder()时也是如此


共 (2) 个答案

  1. # 1 楼答案

    naturalOrder()返回一个Comparator以自然顺序比较Comparable对象

    在您的示例中,它是按字典顺序比较集合的条目。(u为每个字母唱ASCII值

  2. # 2 楼答案

    naturalOrder表示根据Comparator或普通字符串比较顺序,而不是源的遭遇顺序。这是完全不同的事情

    可能是Integer流更容易理解:

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

    遭遇顺序是3, 4, 1, 2

    排序顺序是1, 2, 3, 4——意思是自然地排序(通过Comparator.naturalOrder()