gpt4 book ai didi

java 流 : grouping by and add fields

转载 作者:行者123 更新时间:2023-11-29 10:08:43 25 4
gpt4 key购买 nike

我有一个 MetricGroup 流,其中:

public class MetricGroup {

private String application;
private int uploadedDocs;
private long uploadedKbs;

// getters and setters

}

我需要汇总所有应用程序指标。我的意思是,对于每个应用程序 (MetricGroup.application),我需要将所有 metric.uploadedDocs 添加到 sumMetric.uploadedDocsmetric .uploadedKdssumMetric.uploadedKbs

我发现我需要某种groupingBy

Stream.of(
new MetricGroup("app1", 1,100),
new MetricGroup("app1", 1,300),
new MetricGroup("app2", 1,200)
)
.collect(Collector.groupingBy(MetricGroup::getApplication, accumulator??, combiner??)

结果将是一个流:

< MetricGroup("app1", 2, 400) , MetricGroup("app2", 1, 200) >

有什么想法吗?

最佳答案

您可以按application 分组,然后将结果映射到MetricGroup:

source.stream()
.collect(groupingBy(MetricGroup::getApplication))
.entrySet().stream()
.map(s -> new MetricGroup(s.getKey(),
s.getValue().stream().mapToInt(MetricGroup::getUploadedDocs).sum(),
s.getValue().stream().mapToLong(MetricGroup::getUploadedKbs).sum()))
.collect(Collectors.toList());

关于java 流 : grouping by and add fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54090334/

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