Java List根据属性排序

java 复制代码
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
 
public class TestSort {
    public static void main(String[] args) {
        CityModel city1 = new CityModel();
        city1.setCity_code(1);
 
        CityModel city2 = new CityModel();
        city2.setCity_code(2);
 
        CityModel city3 = new CityModel();
        city3.setCity_code(3);
 
        CityModel city4 = new CityModel();
        city4.setCity_code(4);
 
        CityModel city5 = new CityModel();
        city5.setCity_code(5);
 
        ArrayList<CityModel> list = new ArrayList<>();
        list.add(city4);
        list.add(city1);
        list.add(city2);
        list.add(city5);
        list.add(city3);
 
        Collections.sort(list, new Comparator<CityModel>(){
            public int compare(CityModel o1, CityModel o2) {
                //按照CityModel的city_code字段进行降序排列
                if(o1.getCity_code() < o2.getCity_code()){
                    return -1;
                }
                if(o1.getCity_code() == o2.getCity_code()){
                    return 0;
                }
                return 1;
            }
        });
        for (CityModel cityModel:list) {
            System.out.println(cityModel.getCity_code());
        }
 
    }
}

Java 8 Lambda 根据属性去重

再小的努力,乘以365都很明显!
一个程序员最重要的能力是:写出高质量的代码!!
有道无术,术尚可求也,有术无道,止于术。
无论你是年轻还是年长,所有程序员都需要记住:时刻努力学习新技术,否则就会被时代抛弃!

相关推荐
2301_8135995522 分钟前
Go语言怎么做秒杀系统_Go语言秒杀系统实战教程【实用】
jvm·数据库·python
--fancy4 小时前
股票预测情感分析研究案例分析
python
shughui5 小时前
PyCharm 完整教程(旧版本卸载+旧/新版本下载安装+基础使用,2026最新版附安装包)
ide·python·pycharm
lUie INGA5 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
小糖学代码5 小时前
LLM系列:1.python入门:15.JSON 数据处理与操作
开发语言·python·json·aigc
yejqvow125 小时前
CSS如何控制placeholder文字的颜色_使用--placeholder伪元素
jvm·数据库·python
geBR OTTE5 小时前
SpringBoot中整合ONLYOFFICE在线编辑
java·spring boot·后端
m0_743623925 小时前
HTML怎么创建多语言切换器_HTML语言选择下拉结构【指南】
jvm·数据库·python
Porunarufu6 小时前
博客系统UI自动化测试报告
java
pele6 小时前
Angular 表单中基于下拉选择动态启用字段必填校验的完整实现
jvm·数据库·python