Java如何遍历HashMap呢?
下文笔者讲述Java中遍历HashMap的方法分享,如下所示:
实现思路:
方式1:
使用while循环
方式2:
使用for循环
例:
package com.java265.other;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class test {
/*
* java265.com 定义HashMap的示例分享
*/
public static void main(String[] args) {
HashMap<String, String> m = new HashMap<>();
m.put("name", "java265.com");
m.put("other", "Java教程");
System.out.println("=========方式1==========");
// 方式1
Iterator t = m.entrySet().iterator();
while (t.hasNext()) {
Map.Entry<String, String> a = (Map.Entry) t.next();
System.out.println(a.getKey() + " = " + a.getValue());
}
System.out.println("=========方式2==========");
// 方式2
for (String k : m.keySet()) {
System.out.println(k);
}
for (String v : m.values()) {
System.out.println(v);
}
System.out.println("=========方式3==========");
for (Map.Entry<String, String> entry : m.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
System.out.println("key:" + key + " value:" + value);
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


