java8stream中对List<Map>排序
模拟数据如下
[{"name":"如花","id":6,"age":16,"height":1.68},{"name":"刘⼀","id":1,"age":28,"height":1.92},{"name":"张三","id":3,"age":18,"height":1.75},{"name":"李四","id":5 ,"age":23,"height":1.65},{"name":"陈⼆","id":2,"age":18,"height":1.72},{"name":"李四","id":4,"age":21,"height":1.75}]
/**
* 模拟数据
* @return
* @apiNote
* id:数据库主键id
* name:姓名(String)
* age:年龄(int)
* height:⾝⾼(BigDecimal)单位⽶
*/
private List<Map<String, Object>>getMyData(){
List<Map<String, Object>> list =new ArrayList<>();
Map<String, Object> m1 =new HashMap<>();
m1.put("id",1);
m1.put("name","刘⼀");
m1.put("age",28);
m1.put("height",new BigDecimal("1.92"));
Map<String, Object> m2 =new HashMap<>();
m2.put("id",2);
m2.put("name","陈⼆");
m2.put("age",18);
m2.put("height",new BigDecimal("1.72"));
Map<String, Object> m3 =new HashMap<>();
m3.put("id",3);
m3.put("name","张三");
m3.put("age",18);
m3.put("height",new BigDecimal("1.75"));
Map<String, Object> m4 =new HashMap<>();
m4.put("id",4);
m4.put("name","李四");
m4.put("age",21);
m4.put("height",new BigDecimal("1.75"));
Map<String, Object> m5 =new HashMap<>();
m5.put("id",5);
m5.put("name","王五");
m5.put("age",23);
m5.put("height",new BigDecimal("1.65"));
Map<String, Object> m6 =new HashMap<>();
m6.put("id",6);
m6.put("name","如花");
m6.put("age",16);
m6.put("height",new BigDecimal("1.68"));
list.add(m6);
list.add(m1);
list.add(m3);
list.add(m5);
list.add(m2);
list.add(m4);
return list;
}
BigDecimal 排序
执⾏如下代码
public static void main(String[] args){
List<Map<String, Object>> studentList =getMyData();
// 按⾝⾼升序
List<Map<String, Object>> sortedByHeightAscList = studentList.stream().sorted(Comparatorparing(h ->((BigDecimal) h.get("height")))).collect(List());
sortedByHeightAscList.stream().forEach(item ->{
System.out.("name")+"的⾝⾼:"+ ("height"));
});
System.out.println();
// 按⾝⾼降序
List<Map<String, Object>> sortedByHeightDescList = studentList.stream().sorted((h1, h2)->((BigDec
("height"))pareTo((BigDecimal)("height"))).List());
sortedByHeightDescList.stream().forEach(item ->{
System.out.("name")+"的⾝⾼:"+ ("height"));
});
}
⾝⾼【升序】排列结果
王五的⾝⾼:1.65
如花的⾝⾼:1.68
陈⼆的⾝⾼:1.72
张三的⾝⾼:1.75
李四的⾝⾼:1.75
刘⼀的⾝⾼:1.92
⾝⾼【降序】排列结果
刘⼀的⾝⾼:1.92
张三的⾝⾼:1.75
李四的⾝⾼:1.75
陈⼆的⾝⾼:1.72
如花的⾝⾼:1.68
java stream王五的⾝⾼:1.65
String 排序
按名称升序
输出结果
刘⼀
如花
张三
李四
王五
陈⼆
按名称降序
输出结果
陈⼆
王五
李四
张三
如花
刘⼀
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论