# HashMap集合-遍历方法
先定义好集合:
public static void main(String[] args) { Map<String,String> onemap=new HashMap<String,String>(); map.put("1", "value1"); map.put("2", "value2"); map.put("3", "value3"); map.put("4", "value4");
(1)第一种:推荐,尤其是容量大时(强烈推荐)
System.out.println("\n通过Map.entrySet遍历key和value"); for(Map.Entry<String, String> entry: onemap.entrySet()) { System.out.println("Key: "+ entry.getKey()+ " Value: "+entry.getValue()); }
(2)第二种方法
System.out.println("\n通过Map.entrySet使用iterator遍历key和value: "); Iterator map1it=onemap.entrySet().iterator(); while(emap1it.hasNext()) { Map.Entry<String, String> entry=(Entry<String, String>) map1it.next(); System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue()); } ```
(3)第三种:普通使用,二次取值
System.out.println("\n通过Map.keySet遍历key和value:"); for(String key: onemap.keySet()) { System.out.println("Key: "+key+" Value: "+ onemap.get(key)); }
(4)第四种
System.out.println("\n通过Map.values()遍历所有的value,但不能遍历key"); for(String v:onemap.values()) { System.out.println("The value is "+v); }
(1)通过Map.entrySet遍历key和value的输出结果:
Key: 1 Value: value1 Key: 2 Value: value2 Key: 3 Value: value3 Key: 4 Value: value4
(2)通过Map.entrySet使用iterator遍历key和value的输出结果:
Key: 1 Value: value1 Key: 2 Value: value2 Key: 3 Value: value3 Key: 4 Value: value4
(3)通过Map.keySet遍历key和value的输出结果:
Key: 1 Value: value1 Key: 2 Value: value2 Key: 3 Value: value3 Key: 4 Value: value4
(4)通过Map.values()遍历所有的value,但不能遍历key的输出结果:
The value is value1
The value is value2
The value is value3
The value is value4
希望能对大家有所帮助,有任何问题评论即可,定时为您解决。
原文:https://www.cnblogs.com/saomoumou/p/11333082.html