java 8 stream 操作list对象
List<Map<String,Object>> 根据数组中的map中的某个属性排序
示例:根据map的的一个key正序排序,根据map中的一个key先正序再根据一个key倒序排序
public class Test {
public static void main(String[] args) {
List<Map<String, Object>> data = new ArrayList<>();
Map<String,Object> map1 = new HashMap<>();
map1.put("年份","2019");
map1.put("人数","11");
//JSONObject map2 = new JSONObject();
Map<String,Object> map2 = new HashMap<>();
map2.put("年份","2018");
map2.put("人数","10");
Map<String,Object> map3 = new HashMap<>();
map3.put("年份","2018");
map3.put("人数","20");
data.add(map1);
data.add(map2);
data.add(map3);
// 原始数据
System.out.println(JSON.toJSONString(data));
// 根据年份正序排序
List<Map<String, Object>> collect1 = data.stream().sorted(Comparator.comparing(Test::comparingByYear)).collect(Collectors.toList());
System.out.println(JSON.toJSONString(collect1));
// 根据年份正序之后,再根据人数倒序排序
List<Map<String, Object>> collect2 = data.stream().sorted(Comparator.comparing(Test::comparingByYear).thenComparing(Comparator.comparing(Test::comparingByPeople).reversed())).collect(Collectors.toList());
System.out.println(JSON.toJSONString(collect2));
}
private static String comparingByYear(Map<String, Object> map){
return (String) map.get("年份");
}
private static Integer comparingByPeople(Map<String, Object> map){
return Integer.valueOf(map.get("人数").toString());
}
}