Java中List排序的3種常見方法總結(jié)
前言
在我們程序的編寫中,有時候我們需要在 Java 程序中對 List 集合進行排序操作。比如獲取所有用戶的列表,但列表默認是以用戶編號從小到大進行排序的,而我們的系統(tǒng)需要按照用戶的年齡從大到小進行排序,這個時候,我們就需要對 List 集合進行自定義排序操作了。
List 排序的常見方法有以下 3 種:
使用 Comparable 進行排序;
使用 Comparator 進行排序;
如果是 JDK 8 以上的環(huán)境,也可以使用 Stream 流進行排序。
下面我們分別來看各種排序方法的具體實現(xiàn)。
1.使用 Comparable 排序
創(chuàng)建一個包含了用戶列表的 List 集合,并按用戶的年齡從大到小進行排序,具體實現(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ī)則進行排序 Collections.sort(list); // 創(chuàng)建ObjectMapper對象 ObjectMapper objectMapper = new ObjectMapper(); // 打印 list 集合 list.forEach(p -> { // 將JavaBean對象轉(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 比較器,無需修改原 Person 類,只需要擴充一個 Person 類的比較器就行了,Comparator 的實現(xiàn)方法有以下兩種:
新建 Comparator 比較器;
使用 Comparator 匿名類比較器。
其中,第二種實現(xiàn)方法要更簡潔一些,我們通過下面的具體代碼,來觀察一下二者的區(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對象轉(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 可以使用更簡潔的匿名類的方式,來實現(xiàn)排序功能,具體實現(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對象 ObjectMapper objectMapper = new ObjectMapper(); // 打印 list 集合 list.forEach(p -> { // 將JavaBean對象轉(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 之后可以使用更加簡單的方法 Stream 流來實現(xiàn)排序功能,它的實現(xiàn)只需要一行代碼,具體實現(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對象 ObjectMapper objectMapper = new ObjectMapper(); // 打印 list 集合 list.forEach(p -> { // 將JavaBean對象轉(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é)果,如下圖所示:
擴展:排序字段為 null
使用 Stream 進行排序時,如果排序的字段出現(xiàn) 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對象轉(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é)果,如下圖所示:
想要解決上述問題,需要給 Comparator.comparing 傳遞第二個參數(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, "王五")); }}; // 按照[年齡]排序,但年齡中有一個 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對象轉(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 有兩種實現(xiàn)的寫法,而在 JDK 8 之后的版本,就可以使用 Comparator.comparing 實現(xiàn)排序了,如果排序字段中可能出現(xiàn) null 值,要使用 Comparator.nullsXXX 進行排序處理(否則會報錯)
到此這篇關(guān)于Java中List排序的3種常見方法的文章就介紹到這了,更多相關(guān)Java中List排序方式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springBoot Junit測試用例出現(xiàn)@Autowired不生效的解決
這篇文章主要介紹了springBoot Junit測試用例出現(xiàn)@Autowired不生效的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09SpringBoot集成Aviator實現(xiàn)參數(shù)校驗的代碼工程
Aviator是一個高性能、輕量級的java語言實現(xiàn)的表達式求值引擎,主要用于各種表達式的動態(tài)求值,本文給大家詳細介紹了SpringBoot集成Aviator實現(xiàn)參數(shù)校驗的方法,并通過代碼示例講解的非常詳細,需要的朋友可以參考下2024-11-11java web學習_淺談request對象中g(shù)et和post的差異
下面小編就為大家?guī)硪黄猨ava web學習_淺談request對象中g(shù)et和post的差異。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05