Reputation: 13
Is there a possibility to rework below method using only streams?
public static Map<String, Long> getPeopleFromLines(List<String> lines) {
Map<String, Long> namesWithCounts = new HashMap<>();
for (String line : lines) {
String[] words = line.split(",");
String name = words[3];
Long count = Long.parseLong(words[4]);
if (namesWithCounts.containsKey(name)) {
namesWithCounts.put(name, namesWithCounts.get(name) + count);
} else {
namesWithCounts.put(name, count);
}
}
return namesWithCounts;
}
Upvotes: 0
Views: 59
Reputation: 40057
And here is yet another way for your learning enjoyment.
public static Map<String, Long> getPeopleFromLines(List<String> lines) {
return lines.stream().map(line -> line.split(","))
.collect(Collectors.groupingBy(arr -> arr[3],
Collectors.summingLong(arr -> Long.valueOf(arr[4]))));
}
Upvotes: 3
Reputation: 6145
Not only is it possible, it’s surprisingly straightforward:
public static Map<String, Long> getPeopleFromLines(List<String> lines) {
return lines.stream()
.map(line -> line.split(","))
.collect(Collectors.toMap(
words -> words[3],
words -> Long.parseLong(words[4]),
Long::sum));
}
Upvotes: 2