Roberto Fernandez Diaz
Roberto Fernandez Diaz

Reputation: 804

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.

Upvotes: 6

Views: 6740

Answers (4)

Andrew
Andrew

Reputation: 49606

  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.

Upvotes: 3

fps
fps

Reputation: 34460

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();

Upvotes: 5

Nikolas
Nikolas

Reputation: 44398

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.

Upvotes: 4

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

if you insist on entrySet -

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

Upvotes: 2

Related Questions