簡體   English   中英

我如何獲取對象數組的值的總和: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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM