java8 stream自定義分組求和並排序
阿新 • • 發佈:2020-01-24
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())裡面的兩個屬性都相同才合併