gpt4 book ai didi

java - 使用收集器按两个字段分组

转载 作者:行者123 更新时间:2023-11-30 06:41:55 24 4
gpt4 key购买 nike

我有一个java对象记录:

public Record(ZonedDateTime day, int ptid, String name, String category, int amount) {
this.day= day;
this.id= id;
this.name = name;
this.category = category;
this.amount = amount;
}

我正在对 Record 的列表进行分组由他们的 day , 然后创建一个新的 Record它结合了 amount字段并返回 map :

Map<ZonedDateTime, Record> map = tempList.stream().collect(Collectors.groupingBy(Record::getDay,
Collectors.collectingAndThen(
Collectors.reducing((r1, r2) -> new Record(r1.getDay(),Integer.toString(r1.getId),r1.getName(),
r1.getCategory(),r1.getAmount() + r2.getAmount())),
Optional::get)));

我想按 day 对列表进行分组和 category .所以如果daycategory是一样的,我想合并amount新领域 Record就像我已经在做的那样。我需要添加另一个 Collectors.groupingBy子句,但语法一直没有用。我相信返回类型是 Map<ZonedDateTime, Map<String, List<Record>>> .然后我还需要将返回的 map 转换为 List .

我一直试图摆脱这个例子 Group by multiple field names in java 8

最佳答案

您可以使用 Collectors.toMap 来简化整个构造:

Map<List<Object>, Record> map = tempList.stream()
.collect(Collectors.toMap(
r -> List.of(r.getDay(), r.getCategory()), // or Arrays.asList
Record::new,
Record::merge));

诀窍是按组合键分组。在这种情况下,我们使用 List<Object>Record.dayRecord.category . ( List 根据需要实现了 Object.hashCodeObject.equals,因此它可以安全地用作任何 Map 的 key )。

为了减少工作,我们需要一个复制构造函数和一个 merge方法:

public Record(Record r) {
this(r.day, r.name, r.name, r.category, r.amount);
}

public Record merge(Record r) {
this.amount += r.amount;
return this;
}

最后,要返回记录列表,不需要做任何比这更花哨的事情:

List<Record> result = new ArrayList<>(map.values());

关于java - 使用收集器按两个字段分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54333841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com