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

相关推荐
Coder_Boy_7 小时前
Deeplearning4j+ Spring Boot 电商用户复购预测案例
java·人工智能·spring boot·后端·spring
mr_LuoWei20097 小时前
python工具:python代码知识库笔记
数据库·python
weixin_395448917 小时前
cursor日志
人工智能·python·机器学习
踢足球09297 小时前
寒假打卡:2026-2-7
java·开发语言·javascript
闻哥7 小时前
Kafka高吞吐量核心揭秘:四大技术架构深度解析
java·jvm·面试·kafka·rabbitmq·springboot
金牌归来发现妻女流落街头7 小时前
【Springboot基础开发】
java·spring boot·后端
天天爱吃肉82188 小时前
【跨界封神|周杰伦×王传福(陶晶莹主持):音乐创作与新能源NVH测试,底层逻辑竟完全同源!(新人必看入行指南)】
python·嵌入式硬件·算法·汽车
考琪8 小时前
Nginx打印变量到log方法
java·运维·nginx
岱宗夫up8 小时前
Python 数据分析入门
开发语言·python·数据分析
wangjialelele8 小时前
Linux中的进程管理
java·linux·服务器·c语言·c++·个人开发