遍历输出map
程序员文章站
2024-02-17 15:21:52
...
HashMap extends AbstractMap implements Map
方式一:
public static void printMap1(Map<String, String> map) {
System.out.println("\n方法一");
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
用transient关键字标记的成员变量不参与序列化过程。
map.entrySet()源码:
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
这里知识new一个 EntrySet
entrySet是 java中 键-值 对的集合,HashMap的成员类-EntrySet
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {}
entry是map中的一个内部类
interface Entry<K,V> {
K getKey();
V getValue();
}
方式二
public static void printMap2(Map<String, String> map) {
System.out.println("\n方法二");
map.forEach((key, value) -> {
System.out.println(key + " " + value);
});
}
方式三
public static void printMap3(Map<String, String> map) {
System.out.println("\n方法三");
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println(key + " " + map.get(key));
}
}
方式四
public static void printMap4(Map<String, String> map) {
System.out.println("\n方法四");
Set<Map.Entry<String, String>> entries = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
System.out.println(next.getKey() + " " + next.getValue());
}
}
方式五
public static void printMap5(Map<String, String> map) {
System.out.println("\n方法五");
Collection<String> values = map.values();
for (String value : values) {
System.out.println(value);
}
}