HashMap一共有四种遍历方式。
Key和Value
- 使用Iterator进行遍历
public static void printHashMap1(HashMap<Integer, Integer> hashMap) {
Iterator<Map.Entry<Integer, Integer>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Integer> entry = iterator.next();
System.out.print(entry.getKey());
System.out.println(entry.getValue());
}
}
- 直接使用For循环进行遍历
public static void printHashMap2(HashMap<Integer, Integer> hashMap) {
for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()){
System.out.print(entry.getKey());
System.out.println(entry.getValue());
}
}
- 通过key进行遍历所有的值
public static void printHashMap3(HashMap<Integer, Integer> hashMap) {
for (Integer key : hashMap.keySet()){
System.out.print(key);
System.out.println(hashMap.get(key));
}
}
Value
- 遍历获取所有的Value
public static void printHashMap4(HashMap<Integer, Integer> hashMap) {
for (Integer value : hashMap.values()){
System.out.print(value);
}
}
更新HashMap,删除某个Key
public static void removeHashMap(HashMap<Integer, Integer> hashMap) {
Iterator<Map.Entry<Integer, Integer>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Integer> entry = iterator.next();
iterator.remove();
System.out.print(entry.getKey());
System.out.println(entry.getValue());
}
}
网友评论