遍历map的四种方式

package testmap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class TestMap {
    
    public static void main(String[] args){
        Map<Integer,String> m = new HashMap<Integer,String>();
        m.put(1, "a");
        m.put(2, "b");
        m.put(3, "c");
        m.put(4, "d");
        m.put(5, "e");
        m.put(6, "f");
        m.put(7, "g");
        System.err.println(m.size());
        
         // 第一种:
        for(Integer in : m.keySet()){
            
            String s = m.get(in);
            
            System.err.println(in+"第一种"+s);
            
        }
        // 第二种:
        Iterator<Map.Entry<Integer,String>> it = m.entrySet().iterator();
        
        while(it.hasNext()){
            Map.Entry<Integer, String> entry = it.next();
            System.err.println(entry.getKey() + entry.getValue());
            
        }
         // 第三种:推荐,尤其是容量大时
        for(Map.Entry<Integer,String> entry: m.entrySet() ){
            System.err.println(entry.getKey() + entry.getValue());
        }
        
        // 第四种:只能遍历value;
        for(String value : m.values()){
            System.err.println(value);
        }
        
        
        
    }
    
    

}

猜你喜欢

转载自www.cnblogs.com/wei-sha/p/8926393.html