How to increment count in java 8 stream

3837 views java-8
8

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

answered question

1 Answer

2

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)).mapToInt(k -> incr).sum();

posted this

Have an answer?

JD

Please login first before posting an answer.