Roberto Fernandez Roberto Fernandez - 7 months ago 15
Java Question

Counter with lambda over map java8

I am trying to convert this :

Map<String,Long> parties=new HashMap<String,Long>();
parties.add("a",1);
...
Long counter=0l;

for (Long votes : parties.values()){
counter+=votes;
}

return counter;


To lambda in Java8 , I try it with reduce like this :

parties.entrySet().stream().reduce((stringLongEntry, stringLongEntry2) -> Here I Stack)


But I don't know how to continue.

PS: I know I can make it with :
parties.values().stream().count(); but i want to find another approach

Regards , Roberto.

Answer

Try the following expression:

counter = parties.values().stream().map((votes) -> votes).reduce(counter, (a, i) -> a+i);

Moreover there are few mistakes in your code:

  • Using Map<String,Long> parties = new HashMap<>(); is the correct way however your one is ot errorneous.
  • HashMap doesn't have .add(..) method, but .put(..) method:

    parties.put("a",1L);
    
  • Since your value is Long, you have to use 1L or 1l instead of whole 1 to specify a Long value.

Comments