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()
时也是如此
# 1 楼答案
naturalOrder()
返回一个Comparator
以自然顺序比较Comparable
对象在您的示例中,它是按字典顺序比较集合的条目。(u为每个字母唱ASCII值)
# 2 楼答案
naturalOrder
表示根据Comparator
或普通字符串比较顺序,而不是源的遭遇顺序。这是完全不同的事情可能是
Integer
流更容易理解:遭遇顺序是
3, 4, 1, 2
排序顺序是
1, 2, 3, 4
——意思是自然地排序(通过Comparator.naturalOrder()
)