利用TreeMap 不重复 & 有序的特性

  1. 声明map存放key-value
  2. 如果输入的key已经存在map中,更新value即可:map.put(j,map.get(j) + value);
  3. 如果输入的key不存在map中,则直接添加进去map:map.put(key,value)
  4. 最后输出map

import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Map<Integer,Integer> map = new TreeMap<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;// 升序
            }
        });
        while (sc.hasNext()){
            int times = sc.nextInt();// 获取要输入的数组的大小
            for(int i = 1; i <= times;i++){
                // 输入数据
                int key = sc.nextInt();
                int value = sc.nextInt();
                boolean flag = false;//
                // 遍历查看是否已经存在了Map中
                for(Integer j : map.keySet()){
                    if(j == key){
                        flag = true;// 判断是否已经存在map中
                        map.put(j,map.get(j) + value);
                        break;
                    }
                }
                if(flag == false) map.put(key,value);// 如果没有找到,也就是能直接将key-value put进去map中
            }
            // 输出结果
            for(Integer j : map.keySet()){
                System.out.println(j + " " + map.get(j));
            }
            // 清空map集合
            map.clear();
        }
    }
}