常用的遍历map的方法
package com.lxh.config.utils;
import java.util.*;
public class CommonMethods {
public static void main(String[] args) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("id", 1);
map.put("name", "lxh");
map.put("age", 18);
getMap(1, map);
getMap(2, map);
getMap(3, map);
getMap(4, map);
getMap(5, map);
}
public static void getMap(Integer type, Map<String, Object> map) {
if (type == 1) {
System.out.println("============通过map.keySet()的key获取value===========");
Set<String> set = map.keySet();
set.forEach(item -> {
System.out.println(item + ": " + map.get(item));
});
} else if (type == 2) {
System.out.println("============通过map.entrySet()的实体去获取key跟value===========");
Set<Map.Entry<String, Object>> entrySet = map.entrySet();
entrySet.forEach(item -> {
System.out.println(item.getKey() + ": " + item.getValue());
});
} else if (type == 3) {
System.out.println("=============通过迭代器获取key跟value==========");
Set<Map.Entry<String, Object>> entrySet = map.entrySet();
Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
} else if (type == 4) {
System.out.println("============通过map.values()获取value,不能获取key===========");
map.values().forEach(System.out::println);
} else if (type == 5) {
System.out.println("============通过lambda表达式获取key跟value===========");
map.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
}