Java中TreeMap和HashMap的應用和比較

**注意:**TreeMap的寫法可用於Mapreduce中reduce程序中對K,V的排序輸出,K,V在輸出時互換。

package cn.bjut.vlsi.TreeMap;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO 自動生成的方法存根
        TreeMap<Integer,String> treemap = new TreeMap<Integer, String>();
        HashMap<Integer,String> hashmap = new HashMap<Integer,String>();

        treemap.put(1234, "北京");
        treemap.put(345, "南京");
        treemap.put(664, "秦皇島");
        treemap.put(1266, "濟南");
        treemap.put(178, "天津");
        treemap.put(1789, "上海");
        treemap.put(1023, "蘇州");

        hashmap.put(1234, "北京");
        hashmap.put(345, "南京");
        hashmap.put(664, "秦皇島");
        hashmap.put(1266, "濟南");
        hashmap.put(178, "天津");
        hashmap.put(1789, "上海");
        hashmap.put(1023, "蘇州");

        System.out.println("******************TreeMap Output******************");

        Set<Entry<Integer,String>> entrySet = treemap.entrySet();
        for(Entry<Integer,String> ent : entrySet){

            System.out.println(ent.getValue() + " " + ent.getKey());

        }

        System.out.println("******************HashMap Output***********************");

        Set<Entry<Integer,String>> entrySet1 = hashmap.entrySet();
        for(Entry<Integer,String> ent : entrySet1){

            System.out.println(ent.getValue() + " " + ent.getKey());

        }
    }

}

運行結果:

*************TreeMap Output*************
天津 178
南京 345
秦皇島 664
蘇州 1023
北京 1234
濟南 1266
上海 1789
*************HashMap Output******************
濟南 1266
秦皇島 664
北京 1234
蘇州 1023
天津 178
南京 345
上海 1789

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章