我如何获得对象数组的值的总和:java8

Got*_*i92 1 java arrays functional-programming object java-stream

在变量“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 = ?;
Run Code Online (Sandbox Code Playgroud)

Pav*_*ngh 5

使用mapToDouble它将返回DoubleStream并使用getter类的函数从对象中获取值并最终应用sum

Arrays.stream(aa).mapToDouble(ObjectWithDoubleValue::getValue).sum()
Run Code Online (Sandbox Code Playgroud)

其中getValuegetter你的班级的函数

class ObjectWithDoubleValue{
    double a;
    public double getValue(){
        return a;
    }
}
Run Code Online (Sandbox Code Playgroud)

样本

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());
Run Code Online (Sandbox Code Playgroud)

输出 :

6.0
Run Code Online (Sandbox Code Playgroud)