TreeMap 来处理合并和排序。

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        // merge value by key, tree map can handle sorting
        Map<Integer, Integer> numMap = new TreeMap<>();
        for (int i = 0; i < size; i++) {
            int key = sc.nextInt();
            int value = numMap.getOrDefault(key, 0);
            value += sc.nextInt();
            numMap.put(key, value);
        }

        for (Map.Entry<Integer, Integer> entry : numMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}