遍历HashMap的方法

463 阅读1分钟

思路

1.首先创建HashMap对象

2.通过使用HashMap对象添加值

public class Test {
    public static void main(String[] args) {
        HashMap<String,Integer> map = new HashMap<>();
        map.put("张三", 23);
        map.put("李四", 26);
        /**第一种:通过获取keySet获取对应的HashMap值*/
        System.out.println("第一种:通过获取keySet获取对应的HashMap值");
        Set<String> set = map.keySet();//得到所有的key集合
        //遍历HashMap集合
        for (String s : set) {
           Integer i = map.get(s);//得到key对应的value值
           System.out.println(s+"\t"+i);
        }
        
        /**第二种:通过Map.entrySet使用Iterator遍历key和value*/
        System.out.println("第二种:通过Map.entrySet使用Iterator遍历key和value");
        Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
        while(it.hasNext()){
           Map.Entry<String, Integer> entry = it.next();
           System.out.println(entry.getKey()+"\t"+entry.getValue());
        }
        
        /**第三种:推荐,尤其是容量大的时候*/
        System.out.println("第三种:通过Map.entrySet遍历key和value");
        for(Map.Entry<String, Integer> entry:map.entrySet()){
           /**
            * Map.Entry<String, Integer>映射项(键值对)
            * 
            * 有几个方法:用上面的名字entry
            * entry.getKey();  entry.getValue();  entry.setValue();  
            * map.entrySet();	//返回此映射中包含此映射关系的Set视图
            */
            System.out.println(entry.getKey()+"\t"+entry.getValue());
        }
        
        /**第四种:通过Map.Values()遍历所有的value,但是不能遍历key*/
        System.out.println("第四种:通过Map.Values()遍历所有的value,但是不能遍历key");
        for(Integer v:map.values()){
           System.out.println(v);
        }
    }
}