Map遍历的两种方式

第一种: 

Map map = new HashMap(); 
Iterator iter = map.entrySet().iterator(); 
while (iter.hasNext()) { 
    Map.Entry entry = (Map.Entry) iter.next(); 
    Object key = entry.getKey(); 
    Object val = entry.getValue(); 
} 

 效率高,以后一定要使用此种方式!

第二种: 

Map map = new HashMap(); 
Iterator iter = map.keySet().iterator(); 
while (iter.hasNext()) { 
    Object key = iter.next(); 
    Object val = map.get(key); 
}

 效率低,以后尽量少使用!

 

TreeMap 默认是按照自然排序的:

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class TreeMapTest {
    public static void main(String[] args) {
        Map<String, String> map = new TreeMap<String, String>();
        map.put("a", "123");
        map.put("c", "3838");
        map.put("b", "123");

        Iterator<Entry<String, String>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println("key=" + key + " and value=" + value);
        }
    }
}

 运行结果:

key=a and value=123
key=b and value=123
key=c and value=3838

 

你可能感兴趣的:(map)