首页 > 作文

Java中List排序的三种实现方法实例

更新时间:2023-04-04 07:20:21 阅读: 评论:0

目录
前言1.使用 comparable 排序2.使用 comparator 排序2.1 新建 comparator 比较器2.2 匿名类比较器3.使用 stream 流排序总结

前言

在某些特殊的场景下,我们需要在 java 程序中对 list 集合进行排序操作。比如从第三方接口中获取所有用户的列表,但列表默认是以用户编号从小到大进行排序的,而我们的系统需要按照用户的年龄从大到小进行排序,这个时候,我们就需要对 list 集合进行自定义排序操作了。

​list 排序的常见方法有以下 3 种:

使用 comparable 进行排序;使用 comparator 进行排序;如果是 jdk 8 以上的环境,也可以使用 stream 流进行排序。

下面我们分别来看各种排序方法的具体实现。

1.使用 comparable 排序

按照本文设计的场景,我们需要创建一个包含了用户列表的 list 集合,并按用户的年龄从大到小进行排序,具体实现代码如下:

public class listsortexample {    public static void main(string[] args) {        // 创建并初始化 list        list<person> list = new arraylist<person>() {{            add(new person(1, 30, "北京"));            add(new person(2, 20, "西安"));            add(new person(3, 40, "上海"));        }};        // 使用 comparable 自定的规则进行排序        collections.sort(list);        // 打印 list 集合        list.foreach(p -> {            system.out.println(p);        });    }}//  以下 t/get/tostring 使用的是 lombok 的注解@getter@tter@tostringclass person implements comparable<person> {    private int id;    private int age;    private string name;    public person(int id, int age, string name) {        this.id = id;        this.age = age;        this.name = name;    }    @override    public int compareto(person p) {        return p.getage() - this.getage();    }}

以上代码的执行结果,如下图所示:

本方法的核心代码如下:

2.使用 comparator 排序

comparable 是类内部的比较方法,而 comparator 是排序类外部的比较器。使用 comparator 比较器,无需修改原 person 类,只需要扩充一个 person 类的比较器就行了,comparator 的实现方法有以下两种:

新建 comparator 比较器;使用 comparator 匿名类比较器。

其中,第二种实现方法要更简洁一些,我们通过下面的具体代码,来观察一下二者的区别。

2.1 新建 comparator 比较器

public class listsortexample2 {    public static void main(string[] args) {        // 创建并初始化 list       工科专业 list<person> list = new arraylist<person>() {{            add(new person(1, 30, "北京"));            add(new person(2, 20, "西安"));            add(new person(3, 40, "上海"));        }};        // 使用 comparator 比较器排序        collections.sort(list, new personcomparator());        // 打印 list 集合        list.foreach(p -> {            system.out.println(p);        });    }}/** * 新建 person 比较器 */class personcomparator implements comparator<person> {    @override    public int compare(person p1, person p2) {        return p2.getage() - p1.getage();    }}@getter@tter@tostringclass person {    private int id;    private int age;    private string name;    public person(int id, int age, string name) {        th温度计的使用is.id = id;        this.age = age;        this.name = name;    }}

以上代码的执行结果,如下图所示:

本方法的核心实现代码如下:

2.2 匿名类比较器

比较器 comparator 可以使用更简洁的匿名类的方式,来实现排序功能,具体实现代码如下:

public class listsortexample2 {    public static void main(string[] args) {        // 创建并初始化 list        list<person> list = new arraylist<person>() {{            add(new person(1, 30, "北京"));            add(new person(2, 20, "西安"));            add(new person(3, 40, "上海"));        }};        // 使用匿名比较器排序        collections.sort(list, new comparator<person>() {            @override            public int compare(person p1, person p2) {                return p2.getage() - p1.getage();            }        });        // 打印 list 集合        list.foreach(p -> {            system.out.println(p);        });    }}@getter@tter@tostringclass person {    privat文明礼仪名人名言e int id;    private int age;    private string name;    public person(int id, int age, string name) {        this.id = id;        this.age = age;        this.name = name;    }}

以上代码的执行结果,如下图所示:

3.使用 stream 流排序

在 jdk 8 之后可以使用更加简单的方法 stream 流来实现排序功能,它的实现只需要一行代码,具体实现如下:

public class listsortexample3 {    public static void main(string[] args) {        // 创建并初始化 list        list<person> list = new arraylist<person>() {{            add(new person(1, 30, "北京"));            add(new person(2, 20, "西安"));            add(new person(3, 40, "上海"));        }};        // 使用 stream 排序        list = list.stream().sorted(comparator.comparing(person::getage).reverd())                .collect(collectors.tolist());        // 打印 list 集合        list.foreach(p -> {            system.out.println(p);        });    }    @getter    @tter    @tostring    static class person {        private int id;        private int age;        private string name;        public person(int id, int age, string name) {            this.id = id;            this.age = age;            this.name = name;        }    }}

其中 reverd() 表示倒序的意思,如果不使用此方法则是正序。

以上代码的执行结果,如下图所示:

扩展:排序字段为 null

使用 stream 进行排序时,如果排序的孩子生辰八字起名字段出现 null 值就会导致异常发生,具体示例如下:

public class listsortexample4 {    public static void main(string[] args) {        // 创建并初始化 list        list<person> list = new arraylist<person>() {{            add(new person(30, "北京"));            add(new person(10, "西安"));            add(new person(40, "上海"));            add(new person(null, "上海")); // 年龄为 null 值        }};        // 按照[年龄]正序,但年龄中有一个 null 值        list = list.stream().sorted(comparator.comparing(person::getage))                .collect(collectors.tolist());        // 打印 list 集合        list.foreach(p -> {            system.out.println(p);        });    }}@getter@tter@tostringclass person {    priv评ate integer age;    private string name;    public person(integer age, string name) {        this.age = age;        this.name = name;    }}

以上代码的执行结果,如下图所示:

想要解决上述问题,需要给 comparator.comparing 传递第二个参数:comparator.nullsxxx,如下代码所示:

public class listsortexample4 {    public static void main(string[] args) {        // 创建并初始化 list        list<person> list = new arraylist<person>() {{            add(new person(30, "北京"));            add(new person(10, "西安"));            add(new person(40, "上海"));            add(new person(null, "上海"));        }};        // 按照[年龄]正序,但年龄中有一个 null 值        list = list.stream().sorted(comparator.comparing(person::getage,                comparator.nullsfirst(integer::compareto)))                .collect(collectors.tolist());        // 打印 list 集合        list.foreach(p -> {            system.out.println(p);        });    }}@getter@tter@tostringclass person {    private integer age;    private string name;    public person(integer age, string name) {        this.age = age;        this.name = name;    }}

comparator.nullsfirst 表示将排序字段中的 null 值放到集合最前面,如果想要将 null 值放到集合最后面可以使用 comparator.nullslast。

以上代码的执行结果,如下图所示:

总结

本文介绍了 3 种 list 排序的方法,前两种方法常用于 jdk 8 之前的版本,其中比较器 comparator 有两种实现的写法,而在 jdk 8 之后的版本,就可以使用 comparator.comparing 实现排序了,如果排序字段中可能出现 null 值,要使用 comparator.nullsxxx 进行排序处理(否则会报错)。

到此这篇关于java中list排序的三种实现方法的文章就介绍到这了,更多相关javalist排序实现内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

本文发布于:2023-04-04 07:20:19,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/bf2477695d44e807c0ed332bf54ec62e.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:Java中List排序的三种实现方法实例.doc

本文 PDF 下载地址:Java中List排序的三种实现方法实例.pdf

标签:代码   方法   上海   所示
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图