Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counter with lambda over map java8

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.

like image 514
Roberto Fernandez Diaz Avatar asked Apr 17 '16 12:04

Roberto Fernandez Diaz


4 Answers

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();
like image 65
fps Avatar answered Sep 24 '22 22:09

fps


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.

like image 35
Nikolas Charalambidis Avatar answered Sep 24 '22 22:09

Nikolas Charalambidis


  1. parties.values().stream().mapToLong(l -> l).sum();
  2. 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);

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.

like image 29
Andrew Tobilko Avatar answered Sep 25 '22 22:09

Andrew Tobilko


if you insist on entrySet -

parties.entrySet().stream().map(e -> e.getValue()).reduce(0L, (longValue1, longValue2) -> longValue1 + longValue2)
like image 25
Sharon Ben Asher Avatar answered Sep 24 '22 22:09

Sharon Ben Asher