阅读量:2
在Java中,要遍历HashMap,可以使用以下几种方法:
- 使用keySet()和get()方法:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
for (String key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
- 使用entrySet()方法:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
for (Map.Entry entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
- 使用Java 8的forEach()方法和lambda表达式:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
}
}
以上三种方法都可以遍历HashMap,并输出键值对。选择哪种方法取决于你的需求和编码风格。
以上就是关于“java currenthashmap如何遍历”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm