软件编程
位置:首页>> 软件编程>> java编程>> 使用jdk1.8实现将list根据指定的值去分组的操作

使用jdk1.8实现将list根据指定的值去分组的操作

作者:大宝vs  发布时间:2022-10-04 18:12:48 

标签:jdk1.8,list,指定值,分组

我就废话不多说了,大家还是直接看代码吧~


Map<String, List<CommentQuery>> commentList = list.stream().collect(Collectors.groupingBy(CommentQuery::getNewsId));
for (Map.Entry<String, List<CommentQuery>> entry : commentList.entrySet()) {
String key = HOT_LIST_KEY + entry.getKey();
if (entry.getValue().isEmpty()) {
stringRedisTemplate.opsForValue().set(key, "");
} else {
Gson gson = new Gson();
String json = gson.toJson(entry.getValue());
//先删除redis数据然后在插入新的牛评数据
stringRedisTemplate.delete(key);
stringRedisTemplate.opsForValue().set(key, json);
stringRedisTemplate.expire(key, 1, TimeUnit.DAYS);
}
}

补充知识:java8 list集合利用stream 根据元素的指定属性进行分组统计

需求是对指定集合的学生信息,根据班级分组统计每个班所有学生的凭证数量。


   List<HashMap<String, Object>> result = new ArrayList<>();
   List<HashMap<String, Object>> list = getList(countVo);
   list.stream()
       .collect(Collectors.groupingBy(map -> map.get("className"), Collectors.toList()))
       .forEach((key, groupMap) -> {
           HashMap<String, Object> stringObjectHashMap = groupMap.stream().reduce((item1, item2) -> {
           Integer pzListNo = item1.get("pzListNo") == null ? 0 : (Integer) item1.get("pzListNo");
           Integer pzListNo2 = item2.get("pzListNo") == null ? 0 : (Integer) item2.get("pzListNo");

item1.put("pzListNo", pzListNo + pzListNo2);
           return item1;
         }).get();

result.add(stringObjectHashMap);
       });

return result;

来源:https://blog.csdn.net/weixin_41802678/article/details/81558056

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com