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

07-26 03:28