java8流总和倍数

java8 stream sum multiple(java8流总和倍数)
本文介绍了java8流总和倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我很好奇,如何总结java8流中的多个变量.

I am curious, how to sum up multiple variables in a java8 stream.

Integer wCPU = 0;
Double wnetwork = 0.0;
Double wMem = 0.0;

this.slaContractList.forEach(sla -> {
    wCPU += sla.getNumberOfCPUs();
    wnetwork += sla.getNetworkBandwith();
    wMem += sla.getMemory();
});

但是,这不会编译,因为 lambda 表达式中的变量应该是 final.

However, this does not compile as the variable in the lambda expression should be final.

推荐答案

假设 slaContractListSlaContract 对象的列表,它有构造函数 SlaContract(numberOfCPUs, networkBandwith, memory) 你可以:

Assuming slaContractList is a list of SlaContract objects, and it has constructor SlaContract(numberOfCPUs, networkBandwith, memory) you can:

SlaContract sumContract = slaContractList.stream()
    .reduce(new SlaContract(0, 0.0, 0.0), (sla1, sla2) -> {
         return new SlaContract(sla1.getNumberOfCPUs() + sla2.getNumberOfCPUs(), sla1.getworkBandwith() + sla2.getworkBandwith(), sla1.getMemory() + sla2.getMemory());
    });

Double wnetwork = sumContract.getworkBandwith();
Double wMem = sumContract.getMemory();
Integer wCPU = sumContract.getNumberOfCPUs();

相同的解决方案,但对于简单的类:

The same solution, but for simple class:

Point sumPoint = pointsList.stream()
    .reduce(new Point(0, 0), (p1, p2) -> {
         return new Point(p1.x + p2.x, p1.y + p2.y);
    });

这篇关于java8流总和倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to output the decimal in average?(如何平均输出小数?)
Java sum 2 negative numbers(Java求和2个负数)
How to get sum of char values produced in a loop?(如何获得循环中产生的 char 值的总和?)
How can I sum the values associated with a reoccurring key in a hashmap(如何将与哈希图中重复出现的键关联的值相加)
subset sum find all subsets that add up to a number(子集和找到所有加起来为一个数字的子集)
Java 8 Stream add elements to list and sum(Java 8 Stream 将元素添加到列表和求和中)