作者:明明如月学长, **** 博客专家,蚂蚁集团高级 Java 工程师,《性能优化方法论》作者、《解锁大厂思维:剖析《阿里巴巴Java开发手册》》、《再学经典:《EffectiveJava》独家解析》专栏作者。
热门文章推荐:
(1)《人工智能时代,软件工程师们将会被取代?》
(2)《超全人工智能 AI工具导航网站合集》
(3)《如何写出高质量的文章:从战略到战术》
(4)《什么? 你还没用过 Cursor? 智能 AI 代码生成工具 Cursor 安装和使用介绍》
(5)《我的性能方法论》
(6)《无需魔法打开即用的 AI 工具集锦》
本教程将为你展示Java中HashMap的几种典型遍历方式。
如果你使用Java8,由于该版本JDK支持lambda表达式,可以采用第5种方式来遍历。
如果你想使用泛型,可以参考方法3。如果你使用旧版JDK不支持泛型可以参考方法4。
1、 通过ForEach循环进行遍历
mport ;
import ;
import ;
public class Test {
public static void main(String[] args) throws IOException {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
(1, 10);
(2, 20);
// Iterating entries using a For Each loop
for (<Integer, Integer> entry : ()) {
("Key = " + () + ", Value = " + ());
}
}
}
2、 ForEach迭代键值对方式
如果你只想使用键或者值,推荐使用如下方式
import ;
import ;
import ;
public class Test {
public static void main(String[] args) throws IOException {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
(1, 10);
(2, 20);
// 迭代键
for (Integer key : ()) {
("Key = " + key);
}
// 迭代值
for (Integer value : ()) {
("Value = " + value);
}
}
}
3、使用带泛型的迭代器进行遍历
import ;
import ;
import ;
import ;
public class Test {
public static void main(String[] args) throws IOException {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
(1, 10);
(2, 20);
Iterator<<Integer, Integer>> entries = ().iterator();
while (()) {
<Integer, Integer> entry = ();
("Key = " + () + ", Value = " + ());
}
}
}
4、使用不带泛型的迭代器进行遍历
import ;
import ;
import ;
import ;
public class Test {
public static void main(String[] args) throws IOException {
Map map = new HashMap();
(1, 10);
(2, 20);
Iterator<> entries = ().iterator();
while (()) {
entry = () ();
Integer key = (Integer) ();
Integer value = (Integer) ();
("Key = " + key + ", Value = " + value);
}
}
}
5、通过Java8 Lambda表达式遍历
import ;
import ;
import ;
public class Test {
public static void main(String[] args) throws IOException {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
(1, 10);
(2, 20);
((k, v) -> ("key: " + k + " value:" + v));
}
}
输出
key: 1 value:10
key: 2 value:20
英文原文:/blog/iterate-hashmap-using-java
创作不易,如果本文对你有帮助,欢迎点赞、收藏加关注,你的支持和鼓励,是我创作的最大动力。
欢迎加入我的知识星球,知识星球ID:15165241 一起交流学习。
/Z3bAiea,申请时标注来自****。欢迎加入我们的 slack 工作区,在里面可以对ai 和我进行提问。
/t/ai-yx51081/shared_invite/zt-1t8cp1lk3-ZMAFutZcN3PCW~8WQDGjPg