Java 8 比較器:如何對 List 排序
在本文中,我們將看到幾個關(guān)于如何在Java 8中對List進(jìn)行排序的例子。
按字母排序字符串列表
List<String> cities = Arrays.asList(
"Milan",
"london",
"San Francisco",
"Tokyo",
"New Delhi"
);
System.out.println(cities);
//[Milan, london, San Francisco, Tokyo, New Delhi]
cities.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(cities);
//[london, Milan, New Delhi, San Francisco, Tokyo]
cities.sort(Comparator.naturalOrder());
System.out.println(cities);
//[Milan, New Delhi, San Francisco, Tokyo, london]
London的“L”使用小寫字母,是為了更好地突出 Comparator.naturalOrder() (返回首先排序大寫字母的比較器)和 String.CASE_INSENSITIVE_ORDER(返回不區(qū)分大小寫的比較器)之間的差異。
基本上,在Java 7中,我們使用Collection.sort()接受List和最后的Comparator ——在Java 8中,我們有新的 List.sort() 用于接受Comparator。
對整數(shù)列表排序
List<Integer> numbers = Arrays.asList(6, 2, 1, 4, 9);
System.out.println(numbers); //[6, 2, 1, 4, 9]
numbers.sort(Comparator.naturalOrder());
System.out.println(numbers); //[1, 2, 4, 6, 9]
按字符串字段對列表排序
假設(shè)我們有一個Movie類,并且我們要“按標(biāo)題title”對List排序。我們可以使用 Comparator.comparing() ,傳遞一個函數(shù),函數(shù)提取用于排序title的字段——在本例中。
List<Movie> movies = Arrays.asList(
new Movie("Lord of the rings"),
new Movie("Back to the future"),
new Movie("Carlito's way"),
new Movie("Pulp fiction"));
movies.sort(Comparator.comparing(Movie::getTitle));
movies.forEach(System.out::println);
輸出:
Movie{title='Back to the future'}
Movie{title='Carlito's way'} Movie{title='Lord of the rings'} Movie{title='Pulp fiction'}
可能你會注意到我們沒有通過任何Comparator ,但正確排序了List。這是因?yàn)閠itle——提取的字段——是一個字符串,并且字符串實(shí)現(xiàn)了可比較的接口。如果你看看Comparator.comparing()實(shí)現(xiàn),你會看到它對提取的鍵調(diào)用compareTo。
return (Comparator<T> & Serializable)
(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
按double字段對列表排序
以類似的方式,我們可以使用 Comparator.comparingDouble()來比較double值。在示例中,我們想按最高到最低的評分來訂購Movie列表。
List<Movie> movies = Arrays.asList(
new Movie("Lord of the rings", 8.8),
new Movie("Back to the future", 8.5),
new Movie("Carlito's way", 7.9),
new Movie("Pulp fiction", 8.9));
movies.sort(Comparator.comparingDouble(Movie::getRating)
.reversed());
movies.forEach(System.out::println);
我們在Comparator上使用reversed函數(shù),以便反轉(zhuǎn)默認(rèn)的從最低到最高的自然順序。 Comparator.comparingDouble()在內(nèi)部使用Double.compare()。
如果你需要比較int或long,那么你可以分別使用comparingInt()和comparingLong()。
使用自定義比較器對列表排序
在前面的例子中,我們沒有指定任何比較器,因?yàn)闆]有必要,但讓我們看一個例子,例子中我們定義了我們自己的比較器。我們的Movie類有一個新的字段——“starred”——使用第三個構(gòu)造函數(shù)參數(shù)設(shè)置。在示例中,我們要對列表進(jìn)行排序,以便列表頂部為已加星標(biāo)的電影。
List<Movie> movies = Arrays.asList(
new Movie("Lord of the rings", 8.8, true),
new Movie("Back to the future", 8.5, false),
new Movie("Carlito's way", 7.9, true),
new Movie("Pulp fiction", 8.9, false));
movies.sort(new Comparator<Movie>() {
@Override
public int compare(Movie m1, Movie m2) {
if(m1.getStarred() == m2.getStarred()){
return 0;
}
return m1.getStarred() ? -1 : 1;
}
});
movies.forEach(System.out::println);
結(jié)果將是:
Movie{starred=true, title='Lord of the rings', rating=8.8}
Movie{starred=true, title='Carlito's way', rating=7.9} Movie{starred=false, title='Back to the future', rating=8.5} Movie{starred=false, title='Pulp fiction', rating=8.9}
我們當(dāng)然可以使用lambda表達(dá)式而不是Anonymous類,如下所示:
movies.sort((m1, m2) -> {
if(m1.getStarred() == m2.getStarred()){
return 0;
}
return m1.getStarred() ? -1 : 1;
});
我們也可以再次使用Comparator.comparing():
movies.sort(Comparator.comparing(Movie::getStarred, (star1, star2) -> {
if(star1 == star2){
return 0;
}
return star1 ? -1 : 1;
}));
在最新的示例中,Comparator.comparing()將第一個參數(shù)作為提取用于排序的鍵的函數(shù),并將Comparator作為第二個參數(shù)。Comparator 使用提取的鍵進(jìn)行比較,star1和star2真是布爾值,分別表示m1.getStarred()和m2.getStarred()。
用比較鏈排序列表
在最后一個例子中,我們要在頂部加上已加星標(biāo)的電影,然后按評分排序。
List<Movie> movies = Arrays.asList(
new Movie("Lord of the rings", 8.8, true),
new Movie("Back to the future", 8.5, false),
new Movie("Carlito's way", 7.9, true),
new Movie("Pulp fiction", 8.9, false));
movies.sort(Comparator.comparing(Movie::getStarred)
.reversed()
.thenComparing(Comparator.comparing(Movie::getRating)
.reversed())
);
movies.forEach(System.out::println);
輸出是:
Movie{starred=true, title='Lord of the rings', rating=8.8}
Movie{starred=true, title='Carlito's way', rating=7.9} Movie{starred=false, title='Pulp fiction', rating=8.9} Movie{starred=false, title='Back to the future', rating=8.5}
正如你所看到的,我們首先按星標(biāo),然后按評分進(jìn)行排序——兩者都反轉(zhuǎn),因?yàn)槲覀兿胍罡叩闹岛驼嬲牡谝弧?/p>
譯文鏈接:http://www.codeceo.com/article/java-8-comparator-sort-list.html
英文原文:Java 8 Comparator: How to Sort a List
翻譯作者:碼農(nóng)網(wǎng) – 小峰