Java集合可以自定義排序。有兩種方法可以實現自定義排序:使用Comparator接口和Comparable接口。
示例代碼:
import java.util.Comparator;
public class CustomComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
// 自定義比較規則,比如按照數字大小從大到小排序
return o2 - o1;
}
}
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(3);
list.add(1);
list.add(2);
CustomComparator customComparator = new CustomComparator();
Collections.sort(list, customComparator);
System.out.println(list); // 輸出:[3, 2, 1]
}
}
示例代碼:
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) {
// 自定義比較規則,比如按照年齡從小到大排序
return this.age - o.age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 18));
students.add(new Student("Charlie", 25));
Collections.sort(students);
for (Student student : students) {
System.out.println(student);
}
}
}
以上是兩種自定義排序的方法,開發人員可以根據實際需求選擇合適的方法來實現自定義排序。