java根据list中的对象某个属性排序
Posted 魑魅丶魍魉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java根据list中的对象某个属性排序相关的知识,希望对你有一定的参考价值。
1、 Collections.sort
1 public class Test { 2 public static void main(String[] args) throws Exception { 3 CityModel city1 = new CityModel(); 4 city1.setCity_code(1); 5 6 CityModel city2 = new CityModel(); 7 city2.setCity_code(1); 8 9 CityModel city3 = new CityModel(); 10 city3.setCity_code(1); 11 12 CityModel city4 = new CityModel(); 13 city4.setCity_code(1); 14 15 CityModel city5 = new CityModel(); 16 city5.setCity_code(1); 17 18 ArrayList<CityModel> list = new ArrayList<>(); 19 list.add(city1); 20 list.add(city2); 21 list.add(city3); 22 list.add(city4); 23 list.add(city5); 24 25 Collections.sort(list, new Comparator<CityModel>(){ 26 public int compare(CityModel o1, CityModel o2) { 27 //按照CityModel的city_code字段进行降序排列 28 if(o1.getCity_code() < o2.getCity_code()){ 29 return 1; 30 } 31 if(o1.getCity_code() == o2.getCity_code()){ 32 return 0; 33 } 34 return -1; 35 } 36 }); 37 38 System.out.println(list); 39 } 40 }
以上是关于java根据list中的对象某个属性排序的主要内容,如果未能解决你的问题,请参考以下文章