HashMap遍历方法总结
Posted 一名不断学习的程序猿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HashMap遍历方法总结相关的知识,希望对你有一定的参考价值。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MapOperation {
private static Map<String, String> map = new HashMap<String, String>();
static {
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");
map.put("4", "value4");
}
public static void method() {
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key : " + entry.getKey());
System.out.println("value : " + entry.getValue());
}
}
public static void method2() {
for (String key : map.keySet()) {
System.out.println("key : " + key);
System.out.println("value : " + map.get(key));
}
}
public static void method3() {
Iterator<HashMap.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("key : " + entry.getKey());
System.out.println("value : " + entry.getValue());
}
}
public static void method4() {
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println("key : " + key);
System.out.println("value : " + map.get(key));
}
}
public static void method5() {
map.forEach((key, value) -> {
System.out.println("key : " + key);
System.out.println("value : " + value);
});
}
//通过Map.values()遍历所有的value,但不能遍历key"
public static void method6() {
for (String v : map.values()) {
System.out.println("The value is " + v);
}
}
public static void method7() {
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key:" + entry.getKey());
System.out.println(" Value:" + entry.getValue());
}
}
}
以上是关于HashMap遍历方法总结的主要内容,如果未能解决你的问题,请参考以下文章