第一种方式,直接比较
根据年龄大小来比较:
list = list.stream()
.sorted((p1, p2) -> p1.getAge() - p2.getAge())
.collect(Collectors.toList());
第二种方式,通过stream的接口指定排序类型操作
list = list.stream()
.sorted(Comparator.comparingInt(Person::getAge))
.collect(Collectors.toList());
第三种方式,通过stream的接口不指定排序类型操作,reversed:反向排序,默认正向排序
list = energyLogList.stream()
.sorted(Comparator.comparing(EnergyLog::getResult).reversed())
.collect(Collectors.toList());
第四种方式,通过stream自定义Comparator排序
List<ResponseData> result = new ArrayList<>();
...........................
result = result.stream().sorted(new Comparator<ResponseData>() {
@Override
public int compare(ResponseData o1, ResponseData o2) {
try{
Date d1 = DateUtils.getDateOfPattern(o1.getDateTime(),"HH:mm:ss");
Date d2 = DateUtils.getDateOfPattern(o2.getDateTime(),"HH:mm:ss");
return d1.compareTo(d2);
}catch (ParseException e){
e.printStackTrace();
}
return 0;
}
}).collect(Collectors.toList());
第五种方式,通过stream对多个属性进行排序
Map<String,String> map1 = new HashMap<>();
map1.put("custId","1");
map1.put("custName","a");
Map<String,String> map2 = new HashMap<>();
map2.put("custId","2");
map2.put("custName","b");
Map<String,String> map3 = new HashMap<>();
map3.put("custId","3");
map3.put("custName","c");
List<Map<String,String>> rawMkInfoList = new ArrayList<HashMap<String,String>>();
rawList.add(map1);
rawList.add(map2);
rawList.add(map3);
List<Map<String, String>> sortedList = rawList.stream().sorted(
Comparator.comparing(m1 -> ((Map<String, String>) m1).get("custId")
, Comparator.reverseOrder()).thenComparing(m2 -> ((Map<String, String>) m2).get("custName"),
Comparator.reverseOrder())
).collect(Collectors.toList()
);