user3342812
user3342812

Reputation: 343

How to increment count in java 8 stream

I have a Map and List which looks like

int total = 0;
int incr = 10;
Map<String, Boolean> hashMap = new HashMap();
hashMap.put("A", true);
hashMap.put("B", false);
hashMap.put("C", true);

List<String> states = new ArrayList<>();
states.add("A");
states.add("B");
states.add("D");
states.add("E");
states.add("F");

Everytime I find a key from the list in the Map then I want to increment my total by increment value;

states.stream()
            .filter(s -> hashMap.containsKey(s) && hashMap.get(s))
            .forEach((s) -> {total = total + incr;} );

Upvotes: 1

Views: 5718

Answers (1)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

Your variable total must be final (that is: carry the keyword final) or be effectively final (that is: you only assign a value to it once outside of the lambda). Otherwise, you can't use that variable within your lambda expression. You may fix it like this,

int total = states.stream()
    .filter(s -> hashMap.containsKey(s) && hashMap.get(s))
    .mapToInt(k -> incr).sum();

As mentioned in the below comment, this can be further simplified as,

int total = states.stream()
    .filter(s -> hashMap.getOrDefault(s, false))
    .mapToInt(k -> incr).sum();

Upvotes: 6

Related Questions