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;
}
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.
If you are always storing 1 as the value for each key, then the total count will always match the size of the map. You can get it simply with parties.size().
If you store different values for each key, then counting how many values you have in the map is wrong. You should sum them instead:
long total = parties.values().stream().mapToLong(v -> v).sum();
                        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:
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.
parties.values().stream().mapToLong(l -> l).sum();parties.values().stream().reduce(0L, (a, b) -> a + b);parties.entrySet().stream().mapToLong(Map.Entry::getValue).sum();parties.entrySet().stream().mapToLong(Map.Entry::getValue).reduce(0L, (a, b) -> a + b);The explanation for the question in the comments. Here we can write either (Map.Entry<String, Long> i) ->  i.getValue() or i ->  i.getValue(). But it will more readable if we replace it for a method reference like Map.Entry::getValue.
if you insist on entrySet -
parties.entrySet().stream().map(e -> e.getValue()).reduce(0L, (longValue1, longValue2) -> longValue1 + longValue2)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With