The problem I am trying to solve is MapSum
LeetCode Description.
In nutshell, the task is to sum values over keys.
Iterating Map = 117 ms:
Iterator<Entry<String, Integer>> it = _map.entrySet().iterator();
int count = 0;
while(it.hasNext()) {
Entry<String, Integer> entry = it.next();
String key = entry.getKey();
int val = entry.getValue();
if(key.startsWith(prefix)) {
count += val;
}
}
Using Java 8 Streams - 134 ms
int count = _map.keySet().stream()
.filter(key -> key.startsWith(prefix))
.map(str -> _map.get(str))
.mapToInt(Number::intValue)
.sum();
Questions
- Should you avoid Streams where for-loop is possible?
Or have I written the above code in non-streaming
way