java几种排序方式

2年前 (2022) 程序员胖胖胖虎阿
264 0 0

1. 数组排序

Arrrays.sort(list) 默认升序排序

Arrays.sort(list, comparator)默认按照comparator中实现的排序定义进行排序,以下面一个例子为例,则是按照test数组的中每一个元素的第二位进行排序,也即是按照6, 2, 4进行排序

int [][] test = new int[][]{{5, 6, 1}, {1, 2, 2}, {3, 4, 3}};
Arrays.sort(test, Comparator.comparingInt(a -> a[1]));

2. List排序

Collections.sort(list) 使用此方法要求list中存放的对象类实现Comparable接口

Collection.sort(list, comparator) 按照comparator中自定义的排序规则进行排序, 以下面这个例子为例,实现Student类对象先按照id从小到大进行排序,如果id一样,则按照name的字典序进行排序, 样例代码输出为

id:1,name:test1
id:1,name:test2
id:2,name:test
id:2,name:test2
id:3,name:test1
id:4,name:test1
id:5,name:test3

Comparator<Student> stuComparator = new Comparator<Student>() {
    @Override
    public int compare(Student o1, Student o2) {
        if (o1.id == o2.id) {
            return o1.name.compareTo(o2.name);
        }
        return o1.id - o2.id;
    }
};

List<Student> stuList = new ArrayList<>();
stuList.add(new Student(1, "test2"));
stuList.add(new Student(1, "test1"));
stuList.add(new Student(2, "test2"));
stuList.add(new Student(2, "test"));
stuList.add(new Student(3, "test1"));
stuList.add(new Student(4, "test1"));
stuList.add(new Student(5, "test3"));

Collections.sort(stuList, stuComparator);

for (Student stu: stuList) {
    System.out.println(stu.toString());
}
class Student implements  Comparable {
    int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public String toString() {
        return "id:" +id +"," +"name:"+name;
    }

    @Override
    public int compareTo(Object o) {
        return 0;
    }
}

版权声明:程序员胖胖胖虎阿 发表于 2022年11月10日 下午8:24。
转载请注明:java几种排序方式 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...