自学内容网 自学内容网

Java List根据属性排序

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


原文地址:https://blog.csdn.net/weixin_42472027/article/details/143476862

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!