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

相关推荐
傻啦嘿哟4 分钟前
某招聘平台爬虫:爬取招聘岗位数据,分析各城市薪资水平
开发语言·爬虫·python
2501_933670796 分钟前
2026秋招量化分析岗技能栈:Python、SQL、统计建模、回测项目怎么准备
开发语言·python·sql
2601_9620776015 分钟前
python Dejavu库快速识别音频指纹实例探究
python·音乐识别·dejavu库·音频指纹识别·实例探究
yxlalm17 分钟前
Spring AI+RAG 01-项目背景与技术选型
java·人工智能·spring
科技苑32 分钟前
如何用Python编程实现一个简单的Web爬虫?
人工智能·python
程序员清风1 小时前
Java 后端高并发设计:线程池、限流、熔断与降级
java·数据库·oracle
dayDayupbetter1 小时前
Visual C++ 2010安装与使用高手秘籍
python
隐擎fox1 小时前
深入理解网络传输层安全:TLS 指纹识别(JA3/JA4)原理与 Python 协议层检测实战
爬虫·python·网络协议·安全·网络安全·https
医疗信息化王工1 小时前
DataForge:基于 Python 的数据库批量导出 Excel 工具——从架构到部署的全流程实战
数据库·python·excel
Seoyoneh1 小时前
Agentic Workflow编排架构:云客服从“被动响应”迈向“主动执行”的技术实现
java·开发语言·架构