Reputation: 5531
I want to Iterate the hashmap using java Stream and would like to execute an inline function for each key and then sum the value
Map<Integer, Integer> myMap= new HashMap<Integer, Integer>() {{
put(5000, 0);
put(1000, 10);
}};
myMap.entrySet().stream().map(e-> {/* want to fetch the corresponding value and increment by X and find the sum*/ });
Upvotes: 0
Views: 346
Reputation: 27038
Try this. This should work.
final Integer sum = myMap.values()
.stream()
.map(value-> value + X)
.reduce(0, Integer::sum)
iIf you wish to get access to key, try this
myMap.entrySet()
.stream()
.map(entry -> entry.getValue() + X) // you can use entry.getKey() to get access to key
.reduce(0, Integer::sum);
Upvotes: 3
Reputation: 17890
Use mapToInt
to generate an IntStream
and sum
to sum the mapped elements.
myMap.entrySet()
.stream()
.mapToInt(entry -> entry.getValue() + X)
.sum();
Upvotes: 1