重复键的Java 8流总和条目 [英] Java 8 stream sum entries for duplicate keys
问题描述
我正在使用Java 8流按某个键对条目列表进行分组,然后按日期对分组进行排序.我还想做的是折叠"组中具有相同日期的任何两个条目并将它们汇总.我有一个这样的课程(出于示例目的而精简)
I am using Java 8 streams to group a list of entries by a certain key and then sorting the groups by date. What I would like to do in addition is to "collapse" any two entries within a group that have the same date and sum them up. I have a class like this (stripped down for example purposes)
class Thing {
private String key;
private Date activityDate;
private float value;
...
}
然后我将它们分组如下:
Then I'm grouping them like so:
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()));
}
我想做的是,如果任何两个Thing条目具有完全相同的日期,则将这些值的值相加并合拢,这样,
What I would like to do is, if any two Thing entries have the exact same date, sum up the values for those and collapse them down such that,
事物1 日期= 1/1/2017 值= 10
Thing1 Date=1/1/2017 Value=10
事物2 日期= 1/1/2017 值= 20
Thing2 Date=1/1/2017 Value=20
在2017年1月1日变成30.
Turns into 30 for 1/1/2017.
完成这样的事情的最好方法是什么?
What's the best way to accomplish something like that?
推荐答案
我将您的Thing
类稍加更改为使用LocalData
,并添加了一个非常简单的toString
:
I have slightly change your Thing
class to use LocalData
and added a very simple toString
:
@Override
public String toString() {
return " value = " + value;
}
如果我理解正确,那么这就是您所需要的:
If I understood correctly, than this is what you need:
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}}
这篇关于重复键的Java 8流总和条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!