I try to use reduce to sum the HashMap value.
public class Link
{
private double[] flows;
public Link(double[] f) {
setFlows(f);
}
public double[] getFlows() {
return flows;
}
public void setFlows(double[] flows) {
this.flows = flows;
}
public static void main(String argv[])
{
// TEST for reduce on HashMap
HashMap<Integer, Link> id1 = new HashMap<Integer, Link>();
id1.put(1, new Link(new double[]{10,1,30}));
id1.put(2, new Link(new double[]{20,2,3}));
id1.put(3, new Link(new double[]{30,2,3}));
id1.put(4, new Link(new double[]{40,2,30}));
double[] my_sum = new double[3];
for (int i=0; i < 3; ++i)
{
my_sum[i] = id1.entrySet().stream().mapToDouble(e->e.getValue().getFlows()[i]).sum();
}
assert(my_sum[0] == 100);
assert(my_sum[1] == 7);
assert(my_sum[2] == 66);
}
}
In the for loop, I want to sum the value of each array item in the Link class. However, I have the problem with:
local variable defined in enclosing scope must be final or effectively final
Basically I don't want to define a final variable as class member, How to solve it?
Or is there a better to sum the value? (without the for loop?)