姓名升序,若相同则按照年龄升序——集合的几种排序方式(有问必答版)

见者有缘,缘来好运。诚邀各位围观我的博客【CS_GUIDER】:
我的云服务器到期了,所以这里放两个部署在码云和 GitHub 的链接:
https://wlei224.gitee.io (Gitee托管,速度极快)
https://wl2o2o.github.io(Github托管,点击有╰
°▽°
╯)

我的开源博客涵盖了八股文Java基础JVMMySQLLinux框架技术算法以及其他领域的文章,博客域名长期有效!!!如果说对您来说有用,请收藏号链接奥。万分感谢。请放心,开源博客,没有任何套路。

个人博客建站教程长期不定时连载,囊括我基于 Hexo | fluid 主题的搭建版本记录以及搭建踩坑记录,还有基于原 fluid 主题增加的小功能,如果感兴趣,欢迎大家在页脚评论区咨询。
博客文章

不bb,直接上源码

package com.wl2o2o.javau8g;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 实现集合排序的几种方式
 * @Author <a href="https://github.com/wl2o2o">程序员CSGUIDER</a>
 * @From <a href="https://wl2o2o.github.io">CSGUIDER博客</a>
 * @CreateTime 2024/4/15
 */

public class CollectionSort {
    public static class Student implements Comparable<Student>{
        private String name;

        private int age;

        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;}
        public Student(String name, int age) { this.name = name; this.age = age;}
        
        @Override
        public String toString() {
            return "Student {" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }

        // 重写比较规则:按姓名升序,姓名相同按年龄升序
        @Override
        public int compareTo(Student o) {
            int flag = this.name.compareTo(o.name);
            if (flag == 0) {
                return this.age - o.age;
            } else {
                return flag;
            }
        }
    }

    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 20));
        students.add(new Student("Bob", 22));
        students.add(new Student("Judy", 18));
        students.add(new Student("cS", 18));
        students.add(new Student("Alice", 23));
        students.add(new Student("Charlie", 20));

        System.out.println("Before sorting:");
        for (Student student : students) {
            System.out.println(student);
        }

        // 方式一:适用于类已经实现 Compareable 接口,标明这个类具备可排序的能力
        // Student 类实现 Compareable 接口、重写 compareTo 方法
        // Collections.sort(students);
        
        // 方式二:适用于类不具备排序能力,但要求排序时
        // 借助 Comparator 接口,直接实现 compare 方法
        // Collections.sort(students, (o1, o2) -> {
        //     int flag = o1.name.compareTo(o2.name);
        //     if (flag == 0) {
        //         // 升序
        //         return o2.age - o1.age;
        //     } else {
        //         return flag;
        //     }
        // });

        // 方式二优化:(可以通过reversed()方法进行降序)
        // Collections.sort(students, Comparator.comparing(Student::getName).reversed().thenComparing(Student::getAge));

        // 方式三:使用 Stream API + Student 类实现 Comparator 接口,重写 compareTo 方法
        // List<Student> collect = students.stream().sorted().collect(Collectors.toList());
        // collect.forEach(System.out::println);

        // 方式四:使用 Stream API + 自实现 Comparator 接口
        students.stream().sorted((o1, o2)->{
            int flag = o1.name.compareTo(o2.name);
            if (flag == 0) {
                return o1.age - o2.age;
            } else {
                return flag;
            }
        }).collect(Collectors.toList()).forEach(System.out::println);
        
        // 方式四优化:
        // List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getName).thenComparing(Student::getAge)).collect(Collectors.toList());
        // System.out.println("After sorting:");
        // collect.forEach(System.out::println);

        System.out.println("After sorting:");
        for (Student student : students) {
            System.out.println(student);
        }

        System.out.println("All tests passed.");

    }

}

代码解释

如果你对部分代码存有疑惑、集合排序核心原理是怎么样?、评论区留下问题,我来解释,有问必答!

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CS_GUIDER

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值