In Java 8, Stream has a method reduce:
T reduce(T identity, BinaryOperator accumulator);
Is the accumulator operator allowed to mo
This is allowed syntactically, but I think it runs against the design pattern and is a bad idea.
static void accumulatorTest() {
ArrayList points = new ArrayList<>();
points.add(new Point(5, 6));
points.add(new Point(0, 6));
points.add(new Point(1, 9));
points.add(new Point(4, 16));
BinaryOperator sumPoints = new BinaryOperator() {
public Point apply(Point p1, Point p2) {
p2.x += p1.x;
p2.y += p1.y;
return new Point(p2); //return p2 and the list is transformed into running total
}
};
Point sum = points.stream().reduce(new Point(0, 0), sumPoints);
System.out.println(sum);
System.out.println(points);
}
The answer is correct; we get the sum of all of the x and y coordinates. The original list is modified, confirmed by the output:
java.awt.Point[x=10,y=37] [java.awt.Point[x=5,y=6], java.awt.Point[x=5,y=12], java.awt.Point[x=6,y=21], java.awt.Point[x=10,y=37]]