题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
import java.util.Scanner;
import java.util.HashMap;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int account = sc.nextInt();
HashMap<Integer, Integer> map = new HashMap<>();//用hashMap存储不说了
sc.nextLine();
for (int i = 0; i < account; i++) {
String str = sc.nextLine();
String[] ary = str.split(" ");
int k = Integer.parseInt(ary[0]);
int v = Integer.parseInt(ary[1]);
if (map.containsKey(k)) {//当重复时,累加
map.get(k);
map.replace(k, map.get(k) + v);//累加操作
} else
map.put(k, v);
}
map.keySet().stream().sorted().forEach(//主要是这里,把key的集合取出来排序再遍历输出
k -> System.out.println(k + " " + map.get(k))
);
}
}
