Java遍历输出Map
程序员文章站
2024-02-17 15:17:04
...
import java.util.*;
/**
* @author PengHao
* @date 2020-03-23 21:05
*/
public class PrintMap {
private static void printMap1(Map<String, String> map) {
System.out.println("\n方法一");
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println(key + " " + map.get(key));
}
}
private static void printMap2(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());
}
}
private static void printMap3(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());
}
}
private static void printMap4(Map<String, String> map) {
System.out.println("\n方法四");
Collection<String> values = map.values();
for (String value : values) {
System.out.println(value);
}
}
public static void main(String[] args) {
Map<String, String> map = new HashMap<>(3);
map.put("周一", "Monday");
map.put("周二", "Tuesday");
map.put("周三", "Wednesday");
printMap1(map);
printMap2(map);
printMap3(map);
printMap4(map);
}
}
方法一
周一 Monday
周二 Tuesday
周三 Wednesday
方法二
周一 Monday
周二 Tuesday
周三 Wednesday
方法三
周一 Monday
周二 Tuesday
周三 Wednesday
方法四
Monday
Tuesday
Wednesday