我有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
)