新建List
public List<Map<String, Integer>> sort() {
List<Map<String, Integer>> listMap = new ArrayList<>();
for (int i=0; i<4; i++) {
Map map = new HashMap();
map.put("id", (int)(Math.random() * 10));
map.put("age", (int)(Math.random() * 10));
listMap.add(map);
}
return listMap;
}
使用main方法进行排序测试
StringUtils类来自commons-lang包,自己测试自行导入
public static void main(String[] args) {
DemoListMapSort demoListMapSort = new DemoListMapSort();
List<Map<String, Integer>> list = demoListMapSort.sort();
System.out.println("排序前:");
System.out.println(" age:" + StringUtils.join(list.stream().map(e -> e.get("age")).toArray(), ","));
List<Map> listMap = list.stream().sorted((i, j) -> j.get("age") - i.get("age")).collect(Collectors.toList());
System.out.println("排序后:");
System.out.println(" age:" + StringUtils.join(listMap.stream().map(e -> e.get("age")).toArray(), ","));
}
测试结果