如何在 Java 中遍歷 HashMap
Mohammad Irfan
2023年10月12日
Java
Java HashMap
-
在 Java 中使用
entrySet()方法遍歷HashMap -
在 Java 中使用
foreach遍歷HashMap -
在 Java 中使用
keySet()方法遍歷HashMap -
在 Java 中使用
forEach()方法遍歷HashMap -
在 Java 中使用
stream和forEach()方法遍歷HashMap
本教程介紹瞭如何在 Java 中遍歷 HashMap,並列舉了一些示例程式碼來理解它。
遍歷 HashMap 有幾種方法,這裡我們使用 keySet()、entrySet() 和 forEach() 方法等。我們來看看例子。
在 Java 中使用 entrySet() 方法遍歷 HashMap
entrySet() 方法用於獲取 HashMap 中包含的對映的集合檢視。我們將集合檢視收集到迭代器中,並使用 while 迴圈進行迭代。請看下面的例子。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, Integer> entry = (Map.Entry) it.next();
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
}
輸出:
1 = 10
2 = 1020
3 = 300
5 = 500
在 Java 中使用 foreach 遍歷 HashMap
這是另一種遍歷 HasMap 的解決方案。在這裡,我們使用 for-each 迴圈來遍歷 HashMap 的元素。請看下面的例子。
import java.util.HashMap;
import java.util.Map;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
}
輸出:
1 = 10
2 = 1020
3 = 300
5 = 500
在 Java 中使用 keySet() 方法遍歷 HashMap
keySet() 方法用於收集所有的鍵,並建立一個集合,進一步用於遍歷 HashMap 的元素。請看下面的例子。
import java.util.HashMap;
import java.util.Map;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
for (Integer key : map.keySet()) {
System.out.println(key + " = " + map.get(key));
}
}
}
輸出:
1 = 10
2 = 1020
3 = 300
5 = 500
在 Java 中使用 forEach() 方法遍歷 HashMap
我們可以使用 forEach() 方法來遍歷 HashMap 的元素。forEach() 方法是 Java 8 中引入的新方法,可用於 Iteratable 和 Stream 介面中。請看下面的例子。
import java.util.HashMap;
import java.util.Map;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
map.forEach((key, value) -> { System.out.println(key + " = " + value); });
}
}
輸出:
1 = 10
2 = 1020
3 = 300
5 = 500
在 Java 中使用 stream 和 forEach() 方法遍歷 HashMap
我們可以使用流來遍歷元素。在這裡,我們使用 entrySet() 來收集 Hashmap 元素,這些元素將進一步遍歷流的 forEach() 方法。
import java.util.HashMap;
import java.util.Map;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(10, "Ten");
map.put(100, "Hundred");
map.put(1000, "Thousand");
map.entrySet().stream().forEach(System.out::println);
}
}
輸出:
1 = 10
2 = 1020
3 = 300
5 = 500
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe