Java8 stream流式编程对List<Map<String, Object>>类型数据进行简单处理

构造list集合

List<Map<String,Object>> list = Lists.newArrayList();
IntStream.range(1,5).forEach(e->{
    Map<String,Object> map = Maps.newHashMap();
    map.put("name","张三"+(e<3?e:e-1));
    map.put("score", (int)(Math.random()*100)+1);
    list.add(map);
});
System.out.println(list);
输出:[{score=60, name=张三1}, {score=94, name=张三2}, {score=75, name=张三2}, {score=55, name=张三3}]

根据map中的score进行过滤

//过滤分数大于60的元素
List<Map<String, Object>> filterList = list.stream().filter(
    e -> (int) e.get("score") > 60).collect(Collectors.toList());
System.out.println(filterList);
输出:[{score=94, name=张三2}, {score=75, name=张三2}]

根据map中的score进行排序

List<Map<String, Object>> sortList = list.stream().sorted((v1, v2) -> {
    BigInteger b1 = new BigInteger(v1.get("score").toString());
    BigInteger b2 = new BigInteger(v2.get("score").toString());
    return b1.compareTo(b2);
}).collect(Collectors.toList());
System.out.println(sortList);
输出:[{score=55, name=张三3}, {score=60, name=张三1}, {score=75, name=张三2}, {score=94, name=张三2}]

对集合中的map的value值求和

//通过Collect方式
int score = list.stream().collect(Collectors.summingInt(
    e -> Integer.parseInt(e.get("score").toString())));
//通过map方式
int sum = list.stream().mapToInt(e -> Integer.parseInt(e.get("score").toString())).sum();
System.out.println(sum);
输出:284

根据map的name进行分组,并将name相同的score值求和

List<Map<String, Object>> collectList = list.stream().collect(
    Collectors.groupingBy(e -> e.get("name"))).values().stream().map(e -> {
    Map<String, Object> map = e.get(0);
    map.put("score", e.stream().map(
        s -> new BigInteger(s.get("score").toString())).reduce(BigInteger.ZERO, BigInteger::add));
    return map;
}).collect(Collectors.toList());
System.out.println(collectList);
输出:[{score=55, name=张三3}, {score=60, name=张三1}, {score=169, name=张三2}]
posted @ 2020-11-16 17:38  zklymm  阅读(19541)  评论(0编辑  收藏  举报