重复键的Java 8流和条目

clo*_*ker 6 java java-8 java-stream

我使用Java 8流来按特定键对条目列表进行分组,然后按日期对组进行排序.此外,我想要做的是"折叠"组中具有相同日期并总结的任何两个条目.我有一个这样的课程(为了示例目的而被剥离)

class Thing {
    private String key;
    private Date activityDate;
    private float value;
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后我就像这样对它们进行分组:

Map<String, List<Thing>> thingsByKey = thingList.stream().collect(
                Collectors.groupingBy(
                        Thing::getKey,
                        TreeMap::new,
                        Collectors.mapping(Function.identity(), toSortedList())
                ));

private static Collector<Thing,?,List<Thing>> toSortedList() {
        return Collectors.collectingAndThen(toList(),
                l -> l.stream().sorted(Comparator.comparing(Thing::getActivityDate)).collect(toList()));
    }
Run Code Online (Sandbox Code Playgroud)

我想要做的是,如果任何两个Thing条目具有完全相同的日期,则总结这些条目的值并将它们折叠下来,以便

Thing1 Date = 1/1/2017 Value = 10

Thing2 Date = 1/1/2017 Value = 20

2017年1月1日变为30.

完成这样的事情的最佳方法是什么?

Eug*_*ene 5

我稍微更改了您的Thing课程以使用LocalData并添加了一个非常简单的内容toString

@Override
public String toString() {
   return " value = " + value;
}
Run Code Online (Sandbox Code Playgroud)

如果我理解正确,那么这就是您所需要的:

Map<String, TreeMap<LocalDate, Thing>> result = Arrays
            .asList(new Thing("a", LocalDate.now().minusDays(1), 12f), new Thing("a", LocalDate.now(), 12f), new Thing("a", LocalDate.now(), 13f))
            .stream()
            .collect(Collectors.groupingBy(Thing::getKey,
                    Collectors.toMap(Thing::getActivityDate, Function.identity(),
                            (Thing left, Thing right) -> new Thing(left.getKey(), left.getActivityDate(), left.getValue() + right.getValue()),
                            TreeMap::new)));


 System.out.println(result); // {a={2017-06-24= value = 12.0, 2017-06-25= value = 25.0}}
Run Code Online (Sandbox Code Playgroud)