在 Java 中,有多种遍历 Map
的方式。最常用的遍历方法包括使用 for-each
循环、Iterator
迭代器和 Stream API
。以下是几种常见的遍历 Map
的方式:
1. 使用 for-each
循环遍历
这是最常用的方式,使用 for-each
循环遍历 Map
的 entrySet()
。
import ;
import ;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
("A", 1);
("B", 2);
("C", 3);
for (<String, Integer> entry : ()) {
("Key: " + () + ", Value: " + ());
}
}
}
2. 使用 for-each
循环遍历 keySet
使用 for-each
循环遍历 Map
的 keySet()
,然后通过 get
方法获取值。
import ;
import ;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
("A", 1);
("B", 2);
("C", 3);
for (String key : ()) {
Integer value = (key);
("Key: " + key + ", Value: " + value);
}
}
}
3. 使用 for-each
循环遍历 values
使用 for-each
循环遍历 Map
的 values()
,如果只需要访问值而不需要访问键。
import ;
import ;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
("A", 1);
("B", 2);
("C", 3);
for (Integer value : ()) {
("Value: " + value);
}
}
}
4. 使用 Iterator
遍历
使用 Iterator
遍历 Map
的 entrySet()
,适用于需要在遍历过程中进行删除操作的情况。
import ;
import ;
import ;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
("A", 1);
("B", 2);
("C", 3);
Iterator<<String, Integer>> iterator = ().iterator();
while (()) {
<String, Integer> entry = ();
("Key: " + () + ", Value: " + ());
}
}
}
5. 使用 Stream API
遍历 Map
在 Java 8 及以上版本中,可以使用 Stream API
遍历 Map
。
import ;
import ;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
("A", 1);
("B", 2);
("C", 3);
((key, value) -> ("Key: " + key + ", Value: " + value));
// 或者使用 stream
().stream()
.forEach(entry -> ("Key: " + () + ", Value: " + ()));
}
}
6. 使用 Streams API
进行高级操作
Stream API
不仅可以用于遍历,还可以进行过滤、映射等操作。
import ;
import ;
import ;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
("A", 1);
("B", 2);
("C", 3);
// 过滤值大于1的条目
Map<String, Integer> filteredMap = ().stream()
.filter(entry -> () > 1)
.collect((::getKey, ::getValue));
((key, value) -> ("Key: " + key + ", Value: " + value));
}
}
总结
以上是几种常用的遍历 Map
的方法,选择哪种方式取决于具体的需求和代码风格。在需要进行删除操作时,使用 Iterator
会更合适;在进行复杂的流式处理时,Stream API
是一个强大的工具。