服务器之家

服务器之家 > 正文

Java如何实现List自定义排序

时间:2020-09-10 00:46     来源/作者:崔笑颜

实体类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.whty.entity;
 
public class User {
    private int id;
    private String name;
    private int age;
    
    public User(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
 
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

测试类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.whty.test;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
import com.whty.entity.User;
 
public class Test {
    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        list.add(new User(1, "java", 20));
        list.add(new User(2, "spark", 19));
        list.add(new User(3, "hive", 21));
        
        for(User user :list) {
            System.out.println("排序前:" + user.toString());
        }
        //实现排序
        Collections.sort(list, new Comparator<User>() {
            @Override
            public int compare(User u1, User u2) {
                if(u1.getAge() > u2.getAge()) {
                    //return -1:即为正序排序
                    return -1;
                }else if (u1.getAge() == u2.getAge()) {
                    return 0;
                }else {
                    //return 1: 即为倒序排序
                    return 1;
                }
            }
        });
        
        for(User user :list) {
            System.out.println("排序后:" + user.toString());
        }
    }
}

运行结果

排序前:User [id=1, name=java, age=20]
排序前:User [id=2, name=spark, age=19]
排序前:User [id=3, name=hive, age=21]
排序后:User [id=3, name=hive, age=21]
排序后:User [id=1, name=java, age=20]
排序后:User [id=2, name=spark, age=19]

以上就是Java如何实现List自定义排序的详细内容,更多关于Java List自定义排序的资料请关注服务器之家其它相关文章!

原文链接:https://cloud.tencent.com/developer/article/1639912

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
最新idea2020注册码永久激活(激活到2100年)
最新idea2020注册码永久激活(激活到2100年) 2020-07-29
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址 2020-08-12
返回顶部