-1

I want to sum a list of double variable that are values of a Hashmap. But I want to do it with lambda expression not with entrySet or sth else.

HashMap <Integer,Double> h=new HashMap<Integer,Double>();//I've put some key,value pairs in it 

double sum =0.0;
h.forEach((k,v)->{
    sum+=v;
});
System.out.println(sum);

But it says; Local variable sum defined in an enclosing scope must be final or effectively final. How could I solve this?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

1 Answers1

1

Well, as the compiler told you, you can't modify a local variable within a lambda expression.

Instead of using forEach, you can create a Stream<Double> of the values of your Map and sum the elements of that Stream:

double sum = h.values()
              .stream()
              .mapToDouble(Double::doubleValue)
              .sum();
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thank you I know this solution but I just tryna get lambda expressions well. For example this code works correctly but i don't get it also double sum[] ={0}; h2.forEach((k,v)->{ sum[0]+=v; }); System.out.println(sum[0]); – Hatice Yazıcı Nov 05 '17 at 14:37
  • @HaticeYazıcı Using an array to overcome this restriction is usually a bad practice. The reason the code works with an array variable is that assigning to `sum[0]` doesn't change the value of `sum` (which is a reference to an array object). – Eran Nov 05 '17 at 14:39
  • Thank you, I got it well. Lastly which one is more efficient and why; solving it with entrySet or with Stream? – Hatice Yazıcı Nov 05 '17 at 14:44
  • @HaticeYazıcı Using Streams adds some overhead, so I'm assuming it would be slower compared to some loop that iterates over the Map. Whether the difference would be significant, I have no idea. – Eran Nov 05 '17 at 14:46