
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
// 输出结果要求有序!
TreeMap<Integer, Integer> treeMap = new TreeMap<>();
while (scanner.hasNextInt()) {
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
int first = scanner.nextInt();
int second = scanner.nextInt();
treeMap.put(first, treeMap.getOrDefault(first, 0) + second);
}
}
for (Integer key : treeMap.keySet()) {
System.out.println(key + " " + treeMap.get(key));
}
}
}
本文通过一个具体的Java程序示例,介绍了如何使用TreeMap来存储和处理整数键值对数据,并实现有序输出。该程序从标准输入读取数据,使用Scanner进行输入处理,最后按升序打印出所有键值对。
5349

被折叠的 条评论
为什么被折叠?



