java中遍历Map对象的四种方式

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

/**
 * 遍历Map对象
* @author xiaosongsong: 
* @CreateTime 创建时间:2018年7月24日 下午3:58:53 
* 类说明
 */
public class MapDemo1 {

    public static void main(String[] args) {
        Map<String, Integer> map=new HashMap<String, Integer>();
        map.put("1", 1);
        map.put("2", 2);
        map.put("3", 3);
        map.put("4", 4);
        map.put("5", 5);
        map.put("6", 6);
        
        /*方式一:最常用,在键值都需要时使用
        for(Map.Entry<String, Integer> entry:map.entrySet()){
            System.out.println("key="+entry.getKey()+","+"value="+entry.getValue());
        }*/
        
        /*方式二:获取键或值,此方法比entrySet在性能上稍好
        for(String key:map.keySet()){
            System.out.println("key="+key);
        }
        for(Integer value:map.values()){
            System.out.println("value="+value);
        }*/
        
        /*方式三:使用Iterator遍历
        Iterator<Map.Entry<String, Integer>> encries=map.entrySet().iterator();
        while(encries.hasNext()){
            Map.Entry<String, Integer> encry=encries.next();
            System.out.println("key="+encry.getKey()+",value="+encry.getValue());
        }*/
        
        /*方式四:通过键找值,效率低*/
        for(String key:map.keySet()){
            Integer value=map.get(key);
            System.out.println("key="+key+",value="+value);
        }
        
    }
}
 

猜你喜欢

转载自blog.csdn.net/xiao297328/article/details/81188278