利用TreeMap自动排序的特点,以及keySet和Iterator遍历输出。

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int count = sc.nextInt();
        Map<Integer,Integer> map = new TreeMap<>();
        for(int i=0;i<count;i++){
            int k = sc.nextInt();
            int v = sc.nextInt();
            if(map.containsKey(k)){
                map.put(k,map.get(k)+v);
            }
            else {
                map.put(k,v);
            }
        }
        Set<Integer> set = map.keySet();
        Iterator<Integer> it = set.iterator();
        while(it.hasNext()){
            int a = it.next();
            System.out.println(a+" "+map.get(a));
        }
    }
}