Demo以下spa
Map<String, String> map = new HashMap<>(); map.put("key1","data1"); map.put("key2","data2"); map.put("key3","data3"); //第一種方式 System.out.println("經過Map.keySet(),遍歷key,value"); for (String key :map.keySet()) { System.out.println("key:" + key + ",value:" + map.get(key)); } //第二種方式 System.out.println("經過map.entrySet().iterator(),遍歷key,value"); Iterator<Map.Entry<String,String>> it = map.entrySet().iterator(); while(it.hasNext()){ Map.Entry<String,String> next = it.next(); System.out.println("key:" + next.getKey() + ",value:" + next.getValue()); } //第三種方式 System.out.println("經過Map.entrySet(),遍歷key,value;推薦使用尤爲是大容量時"); for(Map.Entry<String,String> entry : map.entrySet()){ System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue()); } //第四種方式 System.out.println("經過Map.values(),遍歷全部的Value,但不能遍歷Key"); for(String v : map.values()){ System.out.println("全部的Value:" + v); }
控制檯輸出3d