• java8 stream自定义分组求和并排序


        public static void main(String[] args) {
            List<GroupDetailDTO> list = new ArrayList<>();
            GroupDetailDTO dto1 = new GroupDetailDTO();
            dto1.setHeadsetId(1);
            dto1.setTime("2020-01-03");
            dto1.setActConcreteTime("a");
            dto1.setPlayed(1);
            list.add(dto1);
    
            GroupDetailDTO dto2 = new GroupDetailDTO();
            dto2.setHeadsetId(1);
            dto2.setTime("2020-01-01");
            dto2.setActConcreteTime("b");
            dto2.setPlayed(1);
            list.add(dto2);
    
            GroupDetailDTO dto3 = new GroupDetailDTO();
            dto3.setHeadsetId(1);
            dto3.setTime("2020-01-02");
            dto3.setActConcreteTime("c");
            dto3.setPlayed(1);
            list.add(dto3);
    
            GroupDetailDTO dto4 = new GroupDetailDTO();
            dto4.setHeadsetId(2);
            dto4.setTime("2020-01-01");
            dto4.setActConcreteTime("d");
            dto4.setPlayed(4);
            list.add(dto4);
    
            Map<GroupDetailDTO, Integer> collect = list.stream().collect(Collectors.groupingBy(o -> new GroupDetailDTO(o.getHeadsetId(), o.getTime()), TreeMap::new, Collectors.summingInt(o -> o.getPlayed())));
            collect.forEach((k, v) -> {
                System.out.println(k + "@@@" + v);
            });
        }
    
    @Data
    public class GroupDetailDTO implements Comparable<GroupDetailDTO> {
        private Integer headsetId;
        private String actConcreteTime;
        private String time;
        private Integer played;
    
        public GroupDetailDTO() {
        }
    
        public GroupDetailDTO(Integer headsetId, String time) {
            this.headsetId = headsetId;
            this.time = time;
        }
    
        @Override
        public int compareTo(GroupDetailDTO o) {
            String a = this.headsetId + "|" + this.getTime();
            String b = o.getHeadsetId() + "|" + o.getTime();
            return a.compareTo(b);
    //        return this.getTime().compareTo(o.gtTime());
        }
    }
    

    结果:

    上述代码实现对对象GroupDetailDTO按设备和时间分组求played的和,并且按时间排序了。当初想着既然是按时间排序那么compareTo方法直接使用
    return this.getTime().compareTo(o.getTime());
    但是结果不正确

    分析:分组求和时如果使用了排序,那么分组时对相同属性的合并将直接根据compareTo返回的结果合并对象,所以如果用上述方法将产生相同的时间直接合并,而不是new GroupDetailDTO(o.getHeadsetId(), o.getTime())里面的两个属性都相同才合并。

  • 相关阅读:
    Gym
    Gym
    Gym
    LA 3713 宇航员分组
    LA 3211 飞机调度(2—SAT)
    POJ 1050 To The Max
    51nod 1050 循环数组最大子段和
    UVa 11149 矩阵的幂(矩阵倍增法模板题)
    POJ 1236 Network of School
    UVa 11324 最大团(强连通分量缩点)
  • 原文地址:https://www.cnblogs.com/shuangyueliao/p/12231703.html
Copyright © 2020-2023  润新知