How to increment count in java 8 stream

user3342812 :

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;} );
Ravindra Ranwala :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114173&siteId=1