Map> commentList = list.stream().collect(Collectors.groupingBy(CommentQuery::getNewsId)); for (Map.Entry > 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> result = new ArrayList<>(); List > list = getList(countVo); list.stream() .collect(Collectors.groupingBy(map -> map.get("className"), Collectors.toList())) .forEach((key, groupMap) -> { HashMap 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;