美文网首页
JAVA 遍历map的几种方法

JAVA 遍历map的几种方法

作者: 妞妞爸爸2018 | 来源:发表于2019-11-07 14:52 被阅读0次

    这种事儿直接上代码吧_

    public static void main(String[] args) {
            //定义map
            Map<String,Object> colorMap = new HashMap<String,Object>();
            colorMap.put("red",   "红色");
            colorMap.put("green", "绿色");
            colorMap.put("blue",  "蓝色");
            colorMap.put("black", "黑色");
            
            //1、使用foreach循环
            readMapForEach(colorMap);
            
            //2、使用迭代
            readMapByIterator(colorMap);
            
            //3、当容量特别大的时候,建议用以下方法
            readBigMap(colorMap);
        }
        
        /**
         * 1、使用foreach循环
         * @param map
         */
        private static final void readMapForEach(Map<String,Object> map){
            //1、使用foreach循环
            //获取key + value
            for (Object key : map.keySet()) {
                String value = (String)map.get(key);
                System.out.println(key + " : " + value);
            }
            //获取value
            for (Object value : map.values()) {
                System.out.println(value);
            }
        }
        
        /**
         * 2、使用迭代
         * @param map
         */
        private static void readMapByIterator(Map<String,Object> map){
            //使用set迭代
            Set set  = map.entrySet();       
            Iterator i  = set.iterator();   
            //判断往下还有没有数据
            while(i.hasNext()){    
                Map.Entry<String, String> entry1 = (Map.Entry<String, String>)i.next();  
                System.out.println(entry1.getKey()+" : "+entry1.getValue());  
            }
            
            //使用keySet()迭代器
            Iterator it = map.keySet().iterator();  
            while(it.hasNext()){  
                String key   = it.next().toString();   
                String value = (String) map.get(key);    
                System.out.println(key + " : " +value);  
            }
                 
            //使用entrySet()迭代器
            Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();
            //判断往下还有没有数据
            while(iter.hasNext()){
                //有的话取出下面的数据
                Entry<String, Object> entry = iter.next();
                String key   = entry.getKey();
                String value = (String)entry.getValue();
                System.out.println(key + " :" + value);
            }
        }
        
        /**
         * 3、当容量特别大的时候,建议用以下方法
         * @param args
         */
        private static void readBigMap(Map<String,Object> map){
            //当容量特别大的时候
            for (Entry<String, Object> entry : map.entrySet()) {
                System.out.println(entry.getKey() + " : " + entry.getValue());
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:JAVA 遍历map的几种方法

          本文链接:https://www.haomeiwen.com/subject/eokvbctx.html