我希望为现有列表创建历史值列表,以便我可以将其保存在数据库中以便稍后在表中显示
Class Data {
Date date;
int int1;
int int2;
}
class DataHistory {
Date date;
int sum_Int1_beforeOrEqualDate;
int sum_Int2_beforeOrEqualDate;
String someOtherValues;
}
例如,我有几行 perDate 包含所有值。我想要实现的是:
我的输入:
date, int1, int2
01/01/18, 2, 3
01/01/18, 0, 1
02/01/18, 0, 1
02/01/18, 3, 0
03/01/18, 1, 3
...
我的输出:
date, sum_Int1_beforeOrEqualDate, sum_Int2_beforeOrEqualDate
01/01/18, 2, 4
02/01/18, 3, 1
03/01/18, 1, 3
...
我尝试过几种方法,主要是用Map,但从来没能用List-->List来做到这一点。
我尝试做的是:
编辑:我的最后一次尝试,这清楚地表明我不知道自己在做什么。
List<OutputList> outputList =
inputlist
.stream()
.map( e -> new DataHistory())
.collect(Collectors.groupingBy(int1));
最佳答案
我相信您正在尝试简单地对按日期分组的值进行求和。因此,假设您已将数据解析为列表
List<Data> list = getDataAsList();
List<DataHistory> historyList = list.stream()
.collect(Collectors.groupingBy(data -> data.date)).entrySet().stream()
.map((entry) -> {
DataHistory history = new DataHistory();
history.date = entry.getKey();
List<Data> dataList = entry.getValue();
history.sum_Int1_beforeOrEqualDate = dataList.stream().mapToInt(data -> data.int1).sum();
history.sum_Int2_beforeOrEqualDate = dataList.stream().mapToInt(data -> data.int2).sum();
return history;
})
.collect(Collectors.toList());
请告诉我逻辑是否正确。
关于Java 8 将一个列表映射到另一个列表并计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49954368/