1

I guess I have a fairly simple question. I have two double arrays and a hash map.

double[] x
double[] y
HashMap<Integer, HashSet<Integer>> myList;

I'd like to get the values for each key and find a summation by using those values in two arrays. However, I keep receiving the scope error. "...defined in an enclosing scope must be final or effectively final"

for (int i = 0; i < size; i++) {
   if ( .... ) {
        double sum = 0; 
        myList.get(i).forEach((val) -> { 
          sum = sum + x[val] + y[val];
        });

        if (sum >= ...) {

        }
}

I placed the variable sum in different places, but could not figure out what I am doing wrong. Could someone help me with that?

sergey_208
  • 614
  • 3
  • 21

2 Answers2

1

You will always get this issue with any primitive type. Change your sum from primitive to some other Object type, where you won't change the reference but can change the value.

For example, it can be a double[1] double array of size 1, then change value at 0th index, Or, AtomicDouble where you can set the value.

GirishB
  • 134
  • 7
0

local variables referenced from a lambda expression must be final or effectively final. Java Documentation

Here is my solution:

    double[] x = new double[] {10.0, 20.0};
    double[] y = new double[] {30.0, 40.0};

    HashMap<Integer, double[]> myList = new HashMap<>();
    myList.put(0, x);
    myList.put(1, y);

    double sum = myList.keySet().stream().map(myList::get)
    .map(doubleArr -> Arrays.stream(doubleArr).reduce(0, (a, b) -> a + b))
    .reduce(0.0, (a, b) -> a + b);

    System.out.println("Result = " + sum);
Ranjeet
  • 116
  • 6