Roberto Fernandez Roberto Fernandez - 2 years ago 121
Java Question

Counter with lambda over map java8

I am trying to convert this :

Map<String,Long> parties=new HashMap<String,Long>();
Long counter=0l;

for (Long votes : parties.values()){

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 Source

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:

  • Since your value is Long, you have to use 1L or 1l instead of whole 1 to specify a Long value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download