盤點Java中的排序操作方案
Comparable 接口-自然排序
-
類implements Comparable接口
-
類重寫 public int compareTo(Object obj)方法
- 如果返回值為正數,則表示當前對象(調用該方法的對象)比 obj 對象“大”;反之“小”;如果為零的話,則表示兩對象相等
public class Student implements Comparable { private int id; private String name; public Student() { super(); } @Override public int compareTo(Object obj) { if (obj instanceof Student) { Student stu = (Student) obj; return id - stu.id; } return 0; } @Override public String toString() { return "<" + id + ", " + name + ">"; } }
- 使用 Arrays 的 sort 方法 對類的對象實例數組 進行排序
Comparator 比較器排序
法1
Arrays.sort方法的參數中增加一個匿名內部類new Comparator(){},在該Comparator中重寫public int compare(Object o1, Object o2)方法,指定按xxx排序
Arrays.sort(stus, new Comparator() { @Override public int compare(Object o1, Object o2) { if (o1 instanceof Student && o2 instanceof Student) { Student s1 = (Student) o1; Student s2 = (Student) o2; //return s1.getId() - s2.getId(); // 按Id排 return s1.getName().compareTo(s2.getName()); // 按姓名排 } return 0; } });
法2
使用TreeSet并指定匿名內部類new Comparator(){},最后把 多個要排序的對象item 添加到 TreeSet中,再打印TreeSet,即得到排序后的數據
Student stu1 = new Student(1, "Little"); Student stu2 = new Student(2, "Cyntin"); Student stu3 = new Student(3, "Tony"); Student stu4 = new Student(4, "Gemini"); SortedSet set = new TreeSet(new Comparator() { @Override public int compare(Object o1, Object o2) { if (o1 instanceof Student && o2 instanceof Student) { Student s1 = (Student) o1; Student s2 = (Student) o2; return s1.getName().compareTo(s2.getName()); } return 0; } }); set.add(stu1); set.add(stu3); set.add(stu2); set.add(stu4); System.out.println(set);
java.util.Collections 工具類
Collections.sort(集合,匿名內部類)方式
public class Main { public static void main(String[] args) { List<Person> people = new ArrayList<>(); // 添加一些 Person 對象到 people List ... // 使用自定義的 Comparator 對 people List 進行排序 Collections.sort(people, new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { return p1.getAge() - p2.getAge(); // 按年齡升序排序 } }); // 打印排序后的 List ... } }
lambda 表達式方式
Collections.sort(people, (p1, p2) -> p1.getAge() - p2.getAge());
Collections.reverse 反轉排序(把一個排好順序的集合進行反轉)
int[] array = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(array); // 注意:這里會返回一個固定大小的List,不支持add/remove操作
// 由于Arrays.asList返回的List是固定大小的,所以我們不能直接反轉它
// 但可以創建一個新的ArrayList并反轉它
List<Integer> arrayList = new ArrayList<>(Arrays.asList(array));
Collections.reverse(arrayList);
// 如果你需要將ArrayList轉回數組
int[] reversedArray = arrayList.stream().mapToInt(Integer::intValue).toArray();
調用Comparator.reverseOrder()反轉排序
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; public class SortIntegers { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); // 生成10個隨機整數 Random random = new Random(); for (int i = 0; i < 10; i++) { numbers.add(random.nextInt(100)); // 假設隨機數的范圍是0到99 } // 打印原始列表 System.out.println("原始列表:"); for (Integer number : numbers) { System.out.print(number + " "); } System.out.println(); // 升序排序并打印 Collections.sort(numbers); System.out.println("升序排序后的列表:"); for (Integer number : numbers) { System.out.print(number + " "); } System.out.println(); // 降序排序并打印 Collections.sort(numbers, Comparator.reverseOrder()); System.out.println("降序排序后的列表:"); for (Integer number : numbers) { System.out.print(number + " "); } System.out.println(); }
}
java8stream寫法
集合.sort()方法
List<Person> people = Arrays.asList(new Person("Alice", 25), new Person("Bob", 20), new Person("Charlie", 30));
people.sort((p1, p2) -> p1.getAge() - p2.getAge()); // 按年齡升序排序
System.out.println(people); // 輸出按年齡排序后的人員列表
自定義排序(使用方法引用)
// 假設Person類有一個靜態方法用于比較年齡 public static int compareByAge(Person p1, Person p2) { return p1.getAge() - p2.getAge(); } List<Person> people = ...; // 初始化人員列表
people.sort(Person::compareByAge); // 使用方法引用進行排序
排序時處理空值或特殊情況
List<String> strings = Arrays.asList("apple", null, "banana", "", "cherry");
strings.sort((s1, s2) -> { if (s1 == null && s2 == null) return 0; if (s1 == null) return 1; if (s2 == null) return -1; if (s1.isEmpty() && s2.isEmpty()) return 0; if (s1.isEmpty()) return 1; if (s2.isEmpty()) return -1; return s1.compareTo(s2);
});
System.out.println(strings); // 輸出排序后的字符串列表,空值和空字符串被放在后面
使用jdframe框架
引入依賴
<dependency><groupId>io.github.burukeyou</groupId><artifactId>jdframe</artifactId><version>0.0.2</version></dependency>
使用內部的排序API
- 準備集合數據
static List<Student> studentList = new ArrayList<>();static {studentList.add(new Student(1,"a","一中","一年級",11, new BigDecimal(1)));studentList.add(new Student(2,"a","一中","一年級",11, new BigDecimal(1)));studentList.add(new Student(3,"b","一中","三年級",12, new BigDecimal(2)));studentList.add(new Student(4,"c","二中","一年級",13, new BigDecimal(3)));studentList.add(new Student(5,"d","二中","一年級",14, new BigDecimal(4)));studentList.add(new Student(6,"e","三中","二年級",14, new BigDecimal(5)));studentList.add(new Student(7,"e","三中","二年級",15, new BigDecimal(5)));
}
- 可以多重排序
// 等價于 order by age desc
SDFrame.read(studentList).sortDesc(Student::getAge);
// 等價于 order by age desc, level asc
SDFrame.read(studentList).sortDesc(Student::getAge).sortAsc(Student::getLevel);
// 等價于 order by age asc
SDFrame.read(studentList).sortAsc(Student::getAge);
// 使用Comparator 排序
SDFrame.read(studentList).sortAsc(Comparator.comparing(e -> e.getLevel() + e.getId()));