TreeMap与HashMap不同点记录

排序

当有多条数据<Integer,Integer>存放到map中,而key值的大小是无序的,那么TreeMap会有一个自动排序的操作

例题

https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201?tpId=37&&tqId=21231&rp=1&ru=/ta/huawei&qru=/ta/huawei/question-ranking

答案


public class Main{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        TreeMap<Integer,Integer> map = new TreeMap();
        while(size>0){
            int key = sc.nextInt();
            int value = sc.nextInt();
            if(map.containsKey(key)){
                map.put(key,map.get(key)+value);
            }else{
                map.put(key,value);
            }
            size--;
        }
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()){
            Map.Entry node = (Map.Entry) iter.next();
            System.out.println(node.getKey()+" "+node.getValue());
        }
    }
}

这个时候用HashMap就不行,题目中要求按顺序输出,如果这里用HashMap的话顺序就会乱。