Counter with lambda over java8 card

I am trying to convert this:

Map<String,Long> parties = new HashMap<>(); parties.add("a", 1); ... Long counter = 0l; for (Long votes : parties.values()){ counter += votes; } 

In lambda in Java8, I try it with a decrease:

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

But I do not know how to proceed.

PS: I know that I can do this: parties.values().stream().count(); but I want to find a different approach

+5
source share
4 answers

Try the following expression:

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

In addition, there are several errors in your code:

  • Using Map<String,Long> parties = new HashMap<>(); is the right way, but yours is wrong.
  • HashMap does not have a .add(..) method, but .put(..) :

     parties.put("a",1L); 
  • Since your value is Long , you should use 1L or 1L instead of the integer 1 to indicate the Long value.

+4
source

If you always save 1 as a value for each key, then the total will always match the size of the card. You can get it simply with parties.size() .

If you save different values ​​for each key, then the calculation of the number of values ​​that you have on the map is incorrect. You must summarize them:

 long total = parties.values().stream().mapToLong(v -> v).sum(); 
+5
source
  • parties.values().stream().mapToLong(l -> l).sum();
  • parties.values().stream().reduce(0L, (a, b) -> a + b);

  1. parties.entrySet().stream().mapToLong(Map.Entry::getValue).sum();
  2. parties.entrySet().stream().mapToLong(Map.Entry::getValue).reduce(0L, (a, b) -> a + b);

Explanation of the issue in the comments. Here we can write either (Map.Entry<String, Long> i) -> i.getValue() , or i -> i.getValue() . But it will be more readable if we replace it with a reference to a method , for example Map.Entry::getValue .

+2
source

if you insist on entrySet -

 parties.entrySet().stream().map(e -> e.getValue()).reduce(0L, (longValue1, longValue2) -> longValue1 + longValue2) 
+2
source

Source: https://habr.com/ru/post/1247307/


All Articles