遍歷HashMap的四種方法


public static void main(String[] args) {
  Map<String,String> map=new HashMap<String,String>();
        map.put("1", "value1");
        map.put("2", "value2");
        map.put("3", "value3");
        map.put("4", "value4");
       
        //第一種:普通使用,二次取值
        System.out.println("\n通過Map.keySet遍歷key和value:"); 
        for(String key:map.keySet())
        {
         System.out.println("Key: "+key+" Value: "+map.get(key));
        }
       
        //第二種
        System.out.println("\n通過Map.entrySet使用iterator遍歷key和value: "); 
        Iterator map1it=map.entrySet().iterator();
        while(map1it.hasNext())
        {
         Map.Entry<String, String> entry=(Entry<String, String>) map1it.next();
         System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue());
        }
       
        //第三種:推薦,尤其是容量大時 
        System.out.println("\n通過Map.entrySet遍歷key和value"); 
        for(Map.Entry<String, String> entry: map.entrySet())
        {
         System.out.println("Key: "+ entry.getKey()+ " Value: "+entry.getValue());
        }
       
        //第四種 
        System.out.println("\n通過Map.values()遍歷所有的value,但不能遍歷key"); 
        for(String v:map.values())
        {
         System.out.println("The value is "+v);
        }

}

輸出結果:

通過Map.keySet遍歷key和value:
Key: 1 Value: value1
Key: 2 Value: value2
Key: 3 Value: value3
Key: 4 Value: value4

通過Map.entrySet使用iterator遍歷key和value: 
Key: 1 Value: value1
Key: 2 Value: value2
Key: 3 Value: value3
Key: 4 Value: value4

通過Map.entrySet遍歷key和value
Key: 1 Value: value1
Key: 2 Value: value2
Key: 3 Value: value3
Key: 4 Value: value4

通過Map.values()遍歷所有的value,但不能遍歷key
The value is value1
The value is value2
The value is value3
The value is value4

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM