Java中List排序的3種常見(jiàn)方法總結(jié)
前言
在我們程序的編寫中,有時(shí)候我們需要在 Java 程序中對(duì) List 集合進(jìn)行排序操作。比如獲取所有用戶的列表,但列表默認(rèn)是以用戶編號(hào)從小到大進(jìn)行排序的,而我們的系統(tǒng)需要按照用戶的年齡從大到小進(jìn)行排序,這個(gè)時(shí)候,我們就需要對(duì) List 集合進(jìn)行自定義排序操作了。
List 排序的常見(jiàn)方法有以下 3 種:
使用 Comparable 進(jìn)行排序;
使用 Comparator 進(jìn)行排序;
如果是 JDK 8 以上的環(huán)境,也可以使用 Stream 流進(jìn)行排序。
下面我們分別來(lái)看各種排序方法的具體實(shí)現(xiàn)。
1.使用 Comparable 排序
創(chuàng)建一個(gè)包含了用戶列表的 List 集合,并按用戶的年齡從大到小進(jìn)行排序,具體實(shí)現(xiàn)代碼如下:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ListSortExample {
public static void main(String[] args) {
// 創(chuàng)建并初始化 List
List<Person> list = new ArrayList<Person>() {{
add(new Person(1, 30, "張三"));
add(new Person(2, 20, "李四"));
add(new Person(3, 40, "王五"));
}};
// 使用 Comparable 自定的規(guī)則進(jìn)行排序
Collections.sort(list);
// 創(chuàng)建ObjectMapper對(duì)象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對(duì)象轉(zhuǎn)換為JSON字符串
String jsonStr = null;
try {
jsonStr = objectMapper.writeValueAsString(p);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(jsonStr);
});
}
}
class Person implements Comparable<Person> {
private int id;
private int age;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name == null ? "" : name;
}
public void setName(String name) {
this.name = name;
}
public Person(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
@Override
public int compareTo(Person p) {
return p.getAge() - this.getAge();
}
}
以上代碼的執(zhí)行結(jié)果,如下圖所示:

2.使用 Comparator 排序
Comparable 是類內(nèi)部的比較方法,而 Comparator 是排序類外部的比較器。使用 Comparator 比較器,無(wú)需修改原 Person 類,只需要擴(kuò)充一個(gè) Person 類的比較器就行了,Comparator 的實(shí)現(xiàn)方法有以下兩種:
新建 Comparator 比較器;
使用 Comparator 匿名類比較器。
其中,第二種實(shí)現(xiàn)方法要更簡(jiǎn)潔一些,我們通過(guò)下面的具體代碼,來(lái)觀察一下二者的區(qū)別。
2.1 新建 Comparator 比較器
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListSortExample {
public static void main(String[] args) {
// 創(chuàng)建并初始化 List
List<Person> list = new ArrayList<Person>() {{
add(new Person(1, 30, "張三"));
add(new Person(2, 20, "李四"));
add(new Person(3, 40, "王五"));
}};
// 使用 Comparator 比較器排序
Collections.sort(list, new PersonComparator());
// 創(chuàng)建ObjectMapper對(duì)象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對(duì)象轉(zhuǎn)換為JSON字符串
String jsonStr = null;
try {
jsonStr = objectMapper.writeValueAsString(p);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(jsonStr);
});
}
}
/**
* 新建 Person 比較器
*/
class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p2.getAge() - p1.getAge();
}
}
class Person {
private int id;
private int age;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name == null ? "" : name;
}
public void setName(String name) {
this.name = name;
}
public Person(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
}
以上代碼的執(zhí)行結(jié)果,如下圖所示:

2.2 匿名類比較器
比較器 Comparator 可以使用更簡(jiǎn)潔的匿名類的方式,來(lái)實(shí)現(xiàn)排序功能,具體實(shí)現(xiàn)代碼如下:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListSortExample {
public static void main(String[] args) {
// 創(chuàng)建并初始化 List
List<Person> list = new ArrayList<Person>() {{
add(new Person(1, 30, "張三"));
add(new Person(2, 20, "李四"));
add(new Person(3, 40, "王五"));
}};
// 使用匿名比較器排序
Collections.sort(list, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p2.getAge() - p1.getAge();
}
});
// 創(chuàng)建ObjectMapper對(duì)象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對(duì)象轉(zhuǎn)換為JSON字符串
String jsonStr = null;
try {
jsonStr = objectMapper.writeValueAsString(p);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(jsonStr);
});
}
}
class Person {
private int id;
private int age;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name == null ? "" : name;
}
public void setName(String name) {
this.name = name;
}
public Person(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
}以上代碼的執(zhí)行結(jié)果,如下圖所示:

3.使用 Stream 流排序
在 JDK 8 之后可以使用更加簡(jiǎn)單的方法 Stream 流來(lái)實(shí)現(xiàn)排序功能,它的實(shí)現(xiàn)只需要一行代碼,具體實(shí)現(xiàn)如下:
package com.highcom.hc.api;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class ListSortExample {
public static void main(String[] args) {
// 創(chuàng)建并初始化 List
List<Person> list = new ArrayList<Person>() {{
add(new Person(1, 30, "張三"));
add(new Person(2, 20, "李四"));
add(new Person(3, 40, "王五"));
}};
// 使用 Stream 排序
list = list.stream().sorted(Comparator.comparing(Person::getAge).reversed())
.collect(Collectors.toList());
// 創(chuàng)建ObjectMapper對(duì)象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對(duì)象轉(zhuǎn)換為JSON字符串
String jsonStr = null;
try {
jsonStr = objectMapper.writeValueAsString(p);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(jsonStr);
});
}
}
class Person {
private int id;
private int age;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name == null ? "" : name;
}
public void setName(String name) {
this.name = name;
}
public Person(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
}其中 reversed() 表示倒序的意思,如果不使用此方法則是正序。
以上代碼的執(zhí)行結(jié)果,如下圖所示:

擴(kuò)展:排序字段為 null
使用 Stream 進(jìn)行排序時(shí),如果排序的字段出現(xiàn) null 值就會(huì)導(dǎo)致異常發(fā)生,具體示例如下:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class ListSortExample {
public static void main(String[] args) {
// 創(chuàng)建并初始化 List
List<Person> list = new ArrayList<Person>() {{
add(new Person(1, 30, "張三"));
add(new Person(2, 20, "李四"));
add(new Person(3, null, "王五"));
}};
// 使用 Stream 排序
list = list.stream().sorted(Comparator.comparing(Person::getAge).reversed())
.collect(Collectors.toList());
// 創(chuàng)建ObjectMapper對(duì)象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對(duì)象轉(zhuǎn)換為JSON字符串
String jsonStr = null;
try {
jsonStr = objectMapper.writeValueAsString(p);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(jsonStr);
});
}
}
class Person {
private int id;
private Integer age;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name == null ? "" : name;
}
public void setName(String name) {
this.name = name;
}
public Person(int id, Integer age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
}
以上代碼的執(zhí)行結(jié)果,如下圖所示:

想要解決上述問(wèn)題,需要給 Comparator.comparing 傳遞第二個(gè)參數(shù):Comparator.nullsXXX,如下代碼所示:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class ListSortExample {
public static void main(String[] args) {
// 創(chuàng)建并初始化 List
List<Person> list = new ArrayList<Person>() {{
add(new Person(1, 30, "張三"));
add(new Person(2, 20, "李四"));
add(new Person(3, null, "王五"));
}};
// 按照[年齡]排序,但年齡中有一個(gè) null 值
list = list.stream().sorted(Comparator.comparing(Person::getAge,
Comparator.nullsFirst(Integer::compareTo)).reversed())
.collect(Collectors.toList());
// 創(chuàng)建ObjectMapper對(duì)象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對(duì)象轉(zhuǎn)換為JSON字符串
String jsonStr = null;
try {
jsonStr = objectMapper.writeValueAsString(p);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(jsonStr);
});
}
}
class Person {
private int id;
private Integer age;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name == null ? "" : name;
}
public void setName(String name) {
this.name = name;
}
public Person(int id, Integer age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
}Comparator.nullsFirst 表示將排序字段中的 null 值放到集合最前面,如果想要將 null 值放到集合最后面可以使用 Comparator.nullsLast。
以上代碼的執(zhí)行結(jié)果,如下圖所示:

總結(jié)
本文介紹了 3 種 List 排序的方法,前兩種方法常用于 JDK 8 之前的版本,其中比較器 Comparator 有兩種實(shí)現(xiàn)的寫法,而在 JDK 8 之后的版本,就可以使用 Comparator.comparing 實(shí)現(xiàn)排序了,如果排序字段中可能出現(xiàn) null 值,要使用 Comparator.nullsXXX 進(jìn)行排序處理(否則會(huì)報(bào)錯(cuò))
到此這篇關(guān)于Java中List排序的3種常見(jiàn)方法的文章就介紹到這了,更多相關(guān)Java中List排序方式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring-cloud入門之eureka-server(服務(wù)發(fā)現(xiàn))
本篇文章主要介紹了spring-cloud入門之eureka-server(服務(wù)發(fā)現(xiàn)),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
10個(gè)Elasticsearch查詢的實(shí)用技巧分享
Elasticsearch是一個(gè)非常流行的搜索引擎,已經(jīng)成為了許多企業(yè)的首選解決方案。本文將向大家介紹10個(gè)實(shí)用的Elasticsearch查詢技巧,并配上對(duì)應(yīng)的代碼示例,希望對(duì)大家有所幫助2023-04-04
java 中設(shè)計(jì)模式(值對(duì)象)的實(shí)例詳解
這篇文章主要介紹了java 中設(shè)計(jì)模式(值對(duì)象)的實(shí)例詳解的相關(guān)資料,希望通過(guò)本文能幫助到大家,需要的朋友可以參考下2017-09-09
Java中SpringSecurity密碼錯(cuò)誤5次鎖定用戶的實(shí)現(xiàn)方法
這篇文章主要介紹了Java中SpringSecurity密碼錯(cuò)誤5次鎖定用戶的實(shí)現(xiàn)方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-03-03
JAVA多線程之實(shí)現(xiàn)用戶任務(wù)排隊(duì)并預(yù)估排隊(duì)時(shí)長(zhǎng)
本文主要介紹了Java多線程之實(shí)現(xiàn)用戶任務(wù)排隊(duì)并預(yù)估排隊(duì)時(shí)長(zhǎng)的問(wèn)題,文中的代碼具有一定的學(xué)習(xí)和工作價(jià)值,感興趣的小伙伴快跟隨小編一起學(xué)習(xí)一下吧2021-12-12
IDEA的Mybatis Generator駝峰配置問(wèn)題
這篇文章主要介紹了IDEA的Mybatis Generator駝峰配置問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
java實(shí)現(xiàn)的根據(jù)概率隨機(jī)中獎(jiǎng)測(cè)試類
這篇文章主要介紹了java實(shí)現(xiàn)的根據(jù)概率隨機(jī)中獎(jiǎng)測(cè)試類,結(jié)合完整實(shí)例形式詳細(xì)分析了java隨機(jī)數(shù)實(shí)現(xiàn)概率運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
RocketMQ實(shí)現(xiàn)消息分發(fā)的步驟
RocketMQ 實(shí)現(xiàn)消息分發(fā)的核心機(jī)制是通過(guò) Topic、Queue 和 Consumer Group 的配合實(shí)現(xiàn)的,下面給大家介紹RocketMQ實(shí)現(xiàn)消息分發(fā)的步驟,感興趣的朋友一起看看吧2024-03-03

