Java中List排序的3種常見方法總結
前言
在我們程序的編寫中,有時候我們需要在 Java 程序中對 List 集合進行排序操作。比如獲取所有用戶的列表,但列表默認是以用戶編號從小到大進行排序的,而我們的系統(tǒng)需要按照用戶的年齡從大到小進行排序,這個時候,我們就需要對 List 集合進行自定義排序操作了。
List 排序的常見方法有以下 3 種:
使用 Comparable 進行排序;
使用 Comparator 進行排序;
如果是 JDK 8 以上的環(huán)境,也可以使用 Stream 流進行排序。
下面我們分別來看各種排序方法的具體實現。
1.使用 Comparable 排序
創(chuàng)建一個包含了用戶列表的 List 集合,并按用戶的年齡從大到小進行排序,具體實現代碼如下:
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ī)則進行排序
Collections.sort(list);
// 創(chuàng)建ObjectMapper對象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對象轉換為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í)行結果,如下圖所示:

2.使用 Comparator 排序
Comparable 是類內部的比較方法,而 Comparator 是排序類外部的比較器。使用 Comparator 比較器,無需修改原 Person 類,只需要擴充一個 Person 類的比較器就行了,Comparator 的實現方法有以下兩種:
新建 Comparator 比較器;
使用 Comparator 匿名類比較器。
其中,第二種實現方法要更簡潔一些,我們通過下面的具體代碼,來觀察一下二者的區(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對象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對象轉換為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í)行結果,如下圖所示:

2.2 匿名類比較器
比較器 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, "王五"));
}};
// 使用匿名比較器排序
Collections.sort(list, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p2.getAge() - p1.getAge();
}
});
// 創(chuàng)建ObjectMapper對象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對象轉換為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í)行結果,如下圖所示:

3.使用 Stream 流排序
在 JDK 8 之后可以使用更加簡單的方法 Stream 流來實現排序功能,它的實現只需要一行代碼,具體實現如下:
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對象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對象轉換為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í)行結果,如下圖所示:

擴展:排序字段為 null
使用 Stream 進行排序時,如果排序的字段出現 null 值就會導致異常發(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對象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對象轉換為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í)行結果,如下圖所示:

想要解決上述問題,需要給 Comparator.comparing 傳遞第二個參數: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, "王五"));
}};
// 按照[年齡]排序,但年齡中有一個 null 值
list = list.stream().sorted(Comparator.comparing(Person::getAge,
Comparator.nullsFirst(Integer::compareTo)).reversed())
.collect(Collectors.toList());
// 創(chuàng)建ObjectMapper對象
ObjectMapper objectMapper = new ObjectMapper();
// 打印 list 集合
list.forEach(p -> {
// 將JavaBean對象轉換為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í)行結果,如下圖所示:

總結
本文介紹了 3 種 List 排序的方法,前兩種方法常用于 JDK 8 之前的版本,其中比較器 Comparator 有兩種實現的寫法,而在 JDK 8 之后的版本,就可以使用 Comparator.comparing 實現排序了,如果排序字段中可能出現 null 值,要使用 Comparator.nullsXXX 進行排序處理(否則會報錯)
到此這篇關于Java中List排序的3種常見方法的文章就介紹到這了,更多相關Java中List排序方式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
spring-cloud入門之eureka-server(服務發(fā)現)
本篇文章主要介紹了spring-cloud入門之eureka-server(服務發(fā)現),小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
Java中SpringSecurity密碼錯誤5次鎖定用戶的實現方法
這篇文章主要介紹了Java中SpringSecurity密碼錯誤5次鎖定用戶的實現方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-03-03

