如何在 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