Java - List排序

时间:2025-01-21 08:26:51

List排序方法

主要有三种方法(按推荐度排序):

  1. JDK8的stream
  2. Comparator#compare()
  3. Comparable#compareTo()

法1:list的sort()

package ;

import ;
import ;
import ;


class User{

    private Integer score;

    private Integer age;

    public User(Integer score, Integer age){
        super();
         = score;
         = age;
    }

    public Integer getScore() {
        return score;
    }

    public void setScore(Integer score) {
         = score;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
         = age;
    }

}


public class Demo {
    public static void main(String[] args) {
        List<User> users = new ArrayList<>();
        (new User(95, 26));
        (new User(84, 23));
        (new User(96, 25));
        (new User(95, 24));

        // 单字段排序
        ((User::getAge));
        for(User user : users){
            (() + "," + ());
        }

        ("---------------------------------");

        // 多字段排序(法1)
        ((o1, o2) -> {
            // 这里必须要在中间加分隔符。否则,若都是数字,会变成数字相加,再转为字符串
            String tmp1 = () + ":" + ();
            String tmp2 = () + ":" + ();
            return (tmp2);
        });
        for(User user : users){
            (() + ":" + ());
        }

        ("---------------------------------");

        // 多字段排序(法2)
        ((o1, o2) -> {
            int i = () - ();
            if (i == 0) {
                return () - ();
            }
            return i;
        });
        for(User user : users){
            (() + "," + ());
        }
    }

}

//测试输出
84,23
95,24
96,25
95,26
---------------------------------
84:23
95:24
95:26
96:25
---------------------------------
96,25
95,24
95,26
84,23

法2:JDK8的stream

方法 说明
sorted() 自然排序(从小到大),流中元素需实现Comparable接口。 例:().sorted()
sorted(Comparator com) 定制排序。常用以下几种:
().sorted(()) //倒序排序(从大到小)
().sorted((Student::getAge)) //顺序排序(从小到大)
().sorted((Student::getAge).reversed()) // 倒序排序(从大到小)

返回排序后的流

//4、sorted:排序,根据名字倒序
().sorted((User::getName).reversed()).collect(()).forEach(::println);

原始类型排序

List<String> list = ("aa", "ff", "dd");
//String 类自身已实现Comparable接口
().sorted().forEach(::println);
 
//结果:
aa
dd
ff

对象单字段排序

User u1 = new User("dd", 40);
User u2 = new User("bb", 20);
User u3 = new User("aa", 20);
User u4 = new User("aa", 30);
List<User> userList = (u1, u2, u3, u4);
 
//按年龄升序
().sorted((User::getAge))
        .forEach(::println);
 
//结果
User(name=bb, age=20)
User(name=aa, age=20)
User(name=aa, age=30)
User(name=dd, age=40)

对象多字段、全部升序排序 

//先按年龄升序,年龄相同则按姓名升序
User u1 = new User("dd", 40);
User u2 = new User("bb", 20);
User u3 = new User("aa", 20);
User u4 = new User("aa", 30);
List<User> userList = (u1, u2, u3, u4);
 
// 写法1(推荐)
().sorted(Comparator
                .comparing(User::getAge)
                .thenComparing(User::getName)
        // 可以写多个.thenComparing
).forEach(::println);
 
("------------------------------------");
 
// 写法2
().sorted(
        (o1, o2) -> {
            String tmp1 = () + ();
            String tmp2 = () + ();
            return (tmp2);
        }
).forEach(::println);
 
("------------------------------------");
 
// 写法3
().sorted(
        (o1, o2) -> {
            if (!().equals(())) {
                return ().compareTo(());
            } else {
                return ().compareTo(());
            }
        }
).forEach(::println);
 
//结果
User(name=aa, age=20)
User(name=bb, age=20)
User(name=aa, age=30)
User(name=dd, age=40)
------------------------------------
User(name=aa, age=20)
User(name=bb, age=20)
User(name=aa, age=30)
User(name=dd, age=40)
------------------------------------
User(name=aa, age=20)
User(name=bb, age=20)
User(name=aa, age=30)
User(name=dd, age=40)

对象多字段、升序+降序

//先按年龄升序,年龄相同则按姓名降序
User u1 = new User("dd", 40);
User u2 = new User("bb", 20);
User u3 = new User("aa", 20);
User u4 = new User("aa", 30);
List<User> userList = (u1, u2, u3, u4);
 
().sorted(
        (o1, o2) -> {
            if (!().equals(())) {
                return ().compareTo(());
            } else {
                return ().compareTo(());
            }
        }
).forEach(::println);
 
//结果
User(name=bb, age=20)
User(name=aa, age=20)
User(name=aa, age=30)
User(name=dd, age=40)

 

法3:Comparator#compare()

需求:用户有成绩和年龄。按成绩排序,若成绩相同,则按年龄排序。

package ;

import ;
import ;
import ;
import ;


class User{

    private int score;

    private int age;

    public User(int score, int age){
        super();
         = score;
         = age;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
         = score;
    }

    public int getAge() {
        return age;
    }

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

}


public class Demo {
    public static void main(String[] args) {
        List<User> users = new ArrayList<User>();
        (new User(95, 26));
        (new User(84, 23));
        (new User(96, 25));
        (new User(95, 24));
        (users, new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                int i = () - ();
                if(i == 0){
                    return () - ();
                }
                return i;
            }
        });
        for(User user : users){
            (() + "," + ());
        }
    }

}

//执行结果
96,25
95,24
95,26
84,23

法4:Comparable#compareTo()

默认按增序排序:

需求:用户有成绩和年龄。按成绩降序排序,若成绩相同,则按年龄正序排序。

package ;

import ;
import ;
import ;


class User implements Comparable<User>{

    private int score;

    private int age;

    public User(int score, int age){
        super();
         = score;
         = age;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
         = score;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public int compareTo(User o) {
        int i = () - ();
        if(i == 0){
            return () - ();
        }
        return i;
    }
}


public class Demo {
    public static void main(String[] args) {
        List<User> users = new ArrayList<User>();
        (new User(95, 26));
        (new User(84, 23));
        (new User(96, 25));
        (new User(95, 24));
        (users);
        for(User user : users){
            (() + "," + ());
        }
    }

}

//执行结果
96,25
95,24
95,26
84,23