gpt4 book ai didi

java - 如何在不获得 Optional 的情况下使用 groupingBy 和 reduce

转载 作者:行者123 更新时间:2023-12-01 14:14:20 25 4
gpt4 key购买 nike

对于我的问题的这个大大简化的例子,我有一个 Stat带有 year 的对象字段和其他三个统计字段。想象一下,结果是来自 vert 链式店分支机构的每种动物类型的患者数量的年度统计数据,我想按年获得所有分支机构的总和。

换句话说,来自 Stat 的列表对象,我想返回一个 Map<Integer, Stat> ,其中整数是年份,而 Stat 对象具有年份和四个字段中每个字段的总和。

public class Stat
{
int year;
public int getYear() { return year; }

long cats;
public long getCats() { return cats; }

long dogs;
public long getDogs() { return dogs; }

long pigeons;
public long getPigeons() { return pigeons; }

public Stat(int year, long cats, long dogs, long pigeons)
{
this.year = year;
this.cats = cats;
this.dogs = dogs;
this.pigeons = pigeons;
}

public Stat(Stat left, Stat right)
{
if (left.year != right.year)
throw new IllegalArgumentException("Only allow combining for same year.");
this.year = left.year;
this.cats = left.cats + right.cats;
this.dogs = left.dogs + right.dogs ;
this.pigeons = left.pigeons + right.pigeons;
}

@Override
public String toString()
{
return String.format("%d c=%d d=%d p=%d", year, cats, dogs, pigeons);
}
}
@Test
public void testStat()
{
List<Stat> items = Arrays.asList(
new Stat(2017, 5, 8, 12),
new Stat(2017, 123, 382, 15),
new Stat(2018, 1, 2, 3)
);
Map<Integer, Optional<Stat>> result = items.stream()
.collect(Collectors.groupingBy(Stat::getYear,
Collectors.reducing(Stat::new)
));
System.out.println(result);
}
Optional没有必要,因为 groupingBy永远不会创建 List需要 reducing如果没有元素。

有没有办法获取 Map<Integer, Stat> ,最好不必创建一个空白的“身份”对象?

如果我不得不求助于创建身份创建功能到 reducing , Stat 对象的组合构造函数必须有年份(见构造函数),那么身份构造函数如何获取传递给它的年份呢?

最佳答案

你宁愿使用 Collectors.toMap 来实现这一点。作为 :

Map<Integer, Stat> result = items.stream()
.collect(Collectors.toMap(Stat::getYear,
Function.identity(), (one, another) -> sumStatsOfSameYear(one, another)));

哪里 sumAttributes被定义为
// stat from the same year
private static Stat sumStatsOfSameYear(Stat one, Stat another) {
new Stat(one.getYear(), one.getCats() + another.getCats(),
one.getDogs() + another.getDogs(), one.getPigeons() + another.getPigeons()))
}

关于java - 如何在不获得 Optional 的情况下使用 groupingBy 和 reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55070139/

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