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

相关推荐
databook1 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
RainbowSea2 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea2 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程
倔强青铜三3 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
考虑考虑6 小时前
Jpa使用union all
java·spring boot·后端
用户3721574261356 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
用户2519162427116 小时前
Python之语言特点
python
刘立军7 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
浮游本尊7 小时前
Java学习第22天 - 云原生与容器化
java