Class A{
Double x;
Double y
}
List aList = new ArrayList<>();//It contains list of A class object.
Now I want to get sum(x-y)
from above list using Java 8.
Thanks in advance
Class A{
Double x;
Double y
}
List aList = new ArrayList<>();//It contains list of A class object.
Now I want to get sum(x-y)
from above list using Java 8.
Thanks in advance
By using Stream API:
import java.util.*;
import java.util.stream.Collectors;
public class TestSum {
static class A{
private Double x;
private Double y;
public A(Double x, Double y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
List<A> aList = new ArrayList<>();
aList.add(new A(2.2, 1.1));
aList.add(new A(3.3, 2.2));
//using converting to DoubleStream
double d1 = aList.stream()
.mapToDouble(a -> a.x-a.y)
.sum();
System.out.println(d1);
//using Collector and getting DoubleSummaryStatistics
double d2 = aList.stream()
.collect(Collectors.summarizingDouble(a-> a.x-a.y))
.getSum();
System.out.println(d2);
}
}
You can try this:
List<A> aList = new ArrayList<>();
A a1 = new A();
a1.x = 5D;
a1.y = 2D;
aList.add(a1);
A a2 = new A();
a2.x = 9D;
a2.y = 2D;
aList.add(a2);
Double sum = aList.stream()
.mapToDouble(a -> a.x - a.y)
.sum();
System.out.println("Sum of x - y of each A of the list: " + sum);
Output is:
Sum of x - y of each A of the list: 10.0
You can use this as well:
Double sumUsingStatistics = aList.stream()
.mapToDouble(a -> a.x - a.y)
.summaryStatistics()
.getSum();
System.out.println("Sum of all x - y of each A of the list: " + sumUsingStatistics);
You will get same output.