HashMap遍历主要有以下四种方式:
- 通过Map的keySet遍历 key和value
- 通过Map.entrySet使用iterator遍历key和value
- 通过Map.entrySet遍历key和value
- 通过Map.values()遍历所有的value,但不能遍历key
public static void main(String[] args) {
HashMap<Integer,String> hashmap = new HashMap<Integer,String>();
hashmap.put(1, "1");
hashmap.put(2, "2");
hashmap.put(3, "3");
hashmap.put(4, "4");
hashmap.put(5, "5");
for(int key :hashmap.keySet()) {
System.out.println("key="+key+" value="+hashmap.get(key));
}
Iterator<Map.Entry<Integer, String>> it = hashmap.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
System.out.println("key="+entry.getKey()+" value="+entry.getValue());
}
for(Map.Entry<Integer, String> entry: hashmap.entrySet()) {
System.out.println("key="+entry.getKey()+" value="+entry.getValue());
}
for(String value: hashmap.values()) {
System.out.println("value="+value);
}
}