Java8stream流式编程对ListMapString,Object》类型数据进⾏简单处理构造list集合
List<Map<String,Object>> list = wArrayList();
IntStream.range(1,5).forEach(e->{
Map<String,Object> map = wHashMap();java stream
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).List());
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 ("score").toString());
BigInteger b2 = new ("score").toString());
return b1pareTo(b2);
}).List());
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.("score").toString())));
//通过map⽅式
int sum = list.stream().mapToInt(e -> Integer.("score").toString())).sum();
System.out.println(sum);
输出:284
根据map的name进⾏分组,并将name相同的score值求和
List<Map<String, Object>> collectList = list.stream().collect(
Map<String, Object> map = e.get(0);
map.put("score", e.stream().map(
s -> new ("score").toString())).reduce(BigInteger.ZERO, BigInteger::add));
return map;
}).List());
System.out.println(collectList);
输出:[{score=55, name=张三3}, {score=60, name=张三1}, {score=169, name=张三2}]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。