使用Comparator实现集合排序

对任意类型集合对象进行整体排序,排序时将此接口的实现传递给Collections.sort方法或者Arrays.sort方法排序.

实现int compare(T o1, T o2);方法,返回正数,零,负数各代表大于,等于,小于。

用于排序的示例代码如下:

实体类:Student

package com.zjx;

public class Student {

    private String username;

    private int age;

    public Student(String username, int age) {
        this.username = username;
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

用于排序的list集合

  List students = new ArrayList() {{
            add(new Student("张三", 12));
            add(new Student("张三", 13));
            add(new Student("张三", 34));
            add(new Student("李四", 54));
            add(new Student("李四", 12));
            add(new Student("王五", 23));
            add(new Student("王五", 21));
        }};

方法一

  //升序
 Collections.sort(students, new Comparator() {
         @Override
         public int compare(Student o1, Student o2) {
            return o1.getAge() - o2.getAge();
         }
 });
 
 
  //降序
 Collections.sort(students, new Comparator() {
         @Override
         public int compare(Student o1, Student o2) {
            return o2.getAge() - o1.getAge();
         }
 });

方法二

升序
Collections.sort(students,(o1,o2) ->(o1.getAge()-o2.getAge()));

降序
Collections.sort(students,(o1,o2) ->(o2.getAge()-o1.getAge()));

方法三

Java8实现方式

 Comparator comparator = Comparator.comparing(Student::getAge);
 
 //升序
 List list = students.stream().sorted(comparator).collect(Collectors.toList());
 
 //倒序
 List list = students.stream().sorted(comparator.reversed()).collect(Collectors.toList());
 

你可能感兴趣的:(java)