Java Arrays自定义排序的五种写法

时间:2025-04-01 19:55:41
package com.javaLearn.customSort_; import java.util.Arrays; import java.util.Comparator; public class Sort01 { public static void main(String[] args) { A[] arr = new A[4]; arr[0] = new A("aaa", 10); arr[1] = new A("cc", 8); arr[2] = new A("dddd", 11); arr[3] = new A("bb", 3); // 类实现Comparable接口 Arrays.sort(arr); System.out.println(Arrays.toString(arr)); // 创建实现Comparator的类/匿名类 Arrays.sort(arr, new Comparator<A>() { @Override public int compare(A o1, A o2) { return o1.getName().compareTo(o2.getName()); } }); System.out.println(Arrays.toString(arr)); Arrays.sort(arr, new Tools()); System.out.println(Arrays.toString(arr)); // 基于Comparator构建Lambda表达式 Comparator<A> comp = (A o1, A o2) -> { return o1.getGrade() - o2.getGrade(); }; Arrays.sort(arr, comp); System.out.println(Arrays.toString(arr)); // Comparator类的comparing方法,可以搭配lambda表达式 Arrays.sort(arr, Comparator.comparing(A::getGrade).thenComparing(A::getName)); System.out.println(Arrays.toString(arr)); Arrays.sort(arr, Comparator.comparing(A::getName, ((o1, o2) -> {return o1.length() - o2.length();}) )); System.out.println(Arrays.toString(arr)); // Comparator类的comparingInt方法,可以搭配lambda表达式,comparing的变体 Arrays.sort(arr, Comparator.comparingInt(o -> o.getName().length())); System.out.println(Arrays.toString(arr)); } } class A implements Comparable<A>{ private String name; private int grade; public A(String name, int grade) { this.name = name; this.grade = grade; } public String getName() { return name; } public int getGrade() { return grade; } @Override public String toString() { return "A{" + "name='" + name + '\'' + ", grade=" + grade + '}'; } @Override public int compareTo(@NotNull A o) { return grade - o.grade; } } class Tools implements Comparator<A> { @Override public int compare(A o1, A o2) { return o1.getGrade() - o2.getGrade(); } }