1. 给非自定义对象排序
public class TestDemo04 {

    public static void main(String[] args) {
        String[] name = {"CCC","BBB", "AAA"};
        Integer[] number = {3, 2, 1};

        // 转换成list
        List<String> nameList = Arrays.asList(name);
        List<Integer> numberList = Arrays.asList(number);
        // 排序
        Collections.sort(nameList);
        Collections.sort(numberList);

        System.out.println(nameList);
        System.out.println(numberList);

    }
}


java 自定义类型排序 java自定义排序list_ide

  1. 给自定义对象排序

通过实现Comparable<T>接口实现

class Person implements Comparable<Person> {

    private Integer id;
    private String name;

    public Person(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public int compareTo(Person o) {
        if (this.id > o.id) {
            return 1;
        } else if (this.id < o.id) {
            return -1;
        } else {
            return 0;
        }
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

测试

public class TestDemo04 {

    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person(3, "CCC"));
        personList.add(new Person(2, "BBB"));
        personList.add(new Person(1, "AAA"));

        // 排序
        Collections.sort(personList);

        System.out.println(personList);
        // this.id > o.id返回1表示如果当前对象id更大,当前对象前移

    }
}


java 自定义类型排序 java自定义排序list_List_02

返回1表示当前对象后移

返回-1表示当前对象前移

返回0表示不移动

  • 通过实现Comparator接口
Comparator comparator = new Comparator<Person>() {
    @Override
    public int compare(Person o1, Person o2) {
        if (o1.getId() > o2.getId()) {
            return 1;
        } else if (o1.getId() < o2.getId()) {
            return -1;
        } else {
            return 0;
        }
    }
};

调用方法:

// 使用一个排序器给List排序,这个排序器是用于给List或List父类排序使用
// Collections.sort(List<T> List, Comparator<? super T> c);
Collections.sort(personList, comparator);