![](/img/trans.png)
[英]How to sum object by time period on a Map object by stream in Java8?
[英]How do i get the sum of values of an Object Array :java8
在變量“ a”中,我創建了一個double
精度數組,在變量“ maxA”中,我獲得了值的總和。 現在在變量“ b”中,我創建一個具有雙精度值的對象數組,現在我想使用stream
值獲得這些值的總和。 感謝幫助
double[] a = new double[] {3.0,1.0};
double maxA = Arrays.stream(a).sum();
ObjectWithDoubleValue o1 = new ObjectWithDoubleValue (3.0);
ObjectWithDoubleValue o2 = new ObjectWithDoubleValue (1.0);
ObjectArray[] b = {o1 , o2};
double maxB = ?;
使用mapToDouble
將返回一個DoubleStream
並使用類的getter
函數從您的對象中獲取值並最終應用sum
Arrays.stream(aa).mapToDouble(ObjectWithDoubleValue::getValue).sum()
其中getValue
是您的類的getter
函數
class ObjectWithDoubleValue{
double a;
public double getValue(){
return a;
}
}
樣品
ObjectWithDoubleValue a1= new ObjectWithDoubleValue();
a1.a=3.0;
ObjectWithDoubleValue a2= new ObjectWithDoubleValue();
a2.a=3.0;
ObjectWithDoubleValue[] aa={a1,a2};
System.out.println(Arrays.stream(aa).mapToDouble(ObjectWithDoubleValue::getValue).sum());
輸出:
6.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.