java8 多字段分组+count
Mysql分组计数
sql语句
SELECT follow_user,action_clue_type,COUNT(DISTINCT clue_id) followClueNum,GROUP_CONCAT(DISTINCT clue_id) FROM crm_clue_follow_record1 WHERE DATE(create_time)=DATE('2021-03-02') AND follow_user=411 GROUP BY follow_user,action_clue_type;
执行结果
java8分组实现
Map<Long, Map<Long, Long>> collect1 = list.stream().collect(Collectors.groupingBy(ClueFollowRecord::getFollowUser, Collectors.groupingBy(ClueFollowRecord::getActionClueType, Collectors.counting()))); Map<Long, Map<Long, List<Long>>> collect = list.stream().collect(Collectors.groupingBy(ClueFollowRecord::getFollowUser, Collectors.groupingBy(ClueFollowRecord::getActionClueType, Collectors.mapping(ClueFollowRecord::getClueId, Collectors.toList())))); System.out.println(JSON.toJSONString(collect1)); System.out.println(JSON.toJSONString(collect));
返回结果:
{411:{161:1,173:1,381:2}} {411:{161:[5106081],173:[2021985],381:[20097,240257]}}
通过java8虽然不能完全实现sql语句相同效果,但是基本可以替代sql语句,也算达到了预期目标。