當我嘗試使用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 orderThisisthenaturalorderAfter orderingThisisnaturalorderthe為什么Comparator.naturalOrder()會有這樣的行為?當我嘗試時也是如此Comparator.reverseOrder()。
2 回答
達令說
TA貢獻1821條經驗 獲得超6個贊
naturalOrder裝置根據到Comparator或純字符串比較次序,不源的遭遇順序。這些是完全不同的東西。
可能是一個 StreamInteger會更容易理解:
Stream.of(3,4,1,2)...
遇到順序是 3, 4, 1, 2
排序順序是1, 2, 3, 4- 意味著自然排序(通過Comparator.naturalOrder())
富國滬深
TA貢獻1790條經驗 獲得超9個贊
naturalOrder()返回按自然順序Comparator比較Comparable對象的a 。
在您的示例中,它按字典順序比較集合的條目。(您為每個字母唱 ASCII 值)。
添加回答
舉報
0/150
提交
取消
