简体   繁体   中英

How do i get the sum of values of an Object Array :java8

in variable "a" i create a double array, and in "maxA" i get the sum of the values. Now in variable "b" i create an object array with double values, now i want to have the sum of these values using the stream value. thanks for help

  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 = ?;

Use mapToDouble which will return a DoubleStream and use getter function of your class to get value from your object and eventually apply sum

Arrays.stream(aa).mapToDouble(ObjectWithDoubleValue::getValue).sum()

where getValue is a getter function of your class

class ObjectWithDoubleValue{
    double a;
    public double getValue(){
        return a;
    }
}

Sample

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());

Output :

6.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM