gpt4 book ai didi

java 流 : straightforward reduce

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:46:42 24 4
gpt4 key购买 nike

我有一个 MetricGroup 流,其中:

public class MetricGroup {

private int uploadedDocs;
private long uploadedKbs;

// getters and setters

}

我需要将所有指标汇总到一个指标中。我的意思是,我需要将所有 metric.uploadedDocs 添加到 sumMetric.uploadedDocs 并将 metric.uploadedKds 添加到 sumMetric.uploadedKbs.

我发现我需要某种reduce

Stream.of(new MetricGroup(1,100), new MetricGroup(1,200))
.reduce(????);

有什么想法吗?

最佳答案

您可以使用 reduce 的重载:

T reduce(T identity,
BinaryOperator<T> accumulator)

像这样:

.reduce(new MetricGroup(0, 0),
(x, y) -> new MetricGroup(
x.getUploadedDocs() + y.getUploadedDocs()
x.getUploadedKbs() + y.getUploadedKbs()
)
)

你也可以使用collect方法:

private static MetricGroup combine(MetricGroup x, MetricGroup y) {
x.setUploadedDocs(x.getUploadedDocs() + y.getUploadedDocs());
x.setUploadedKbs(x.getUploadedKbs() + y.getUploadedKbs());
return x;
}

// ....

.collect(() -> new MetricGroup(0, 0),
YourClass::combine,
YourClass::combine
)

关于java 流 : straightforward reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54089939/

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