getOrDefault & merge
Completed
Read lines team points. Sum points per team using Map.merge (Java 8), and print teams sorted by name with totals.
Input
n, then n lines.
Output
One line per team.
Example
Input
5 red 3 blue 1 red 2 green 0 blue 4
Output
blue 5 green 0 red 5
Editor
Java
Hints
map.merge(key, value, Integer::sum) adds value to the existing total, or inserts it.
Solution explanation
merge and getOrDefault remove the null checks needed in older Java code.
Show solution
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Map<String, Integer> totals = new TreeMap<String, Integer>();
for (int i = 0; i < n; i++) {
String team = sc.next();
int pts = sc.nextInt();
totals.merge(team, pts, Integer::sum);
}
for (Map.Entry<String, Integer> e : totals.entrySet()) {
System.out.println(e.getKey() + " " + e.getValue());
}
}
}