在java中所有的map都实现了Map接口,因此所有的Map(如HashMap, TreeMap, LinkedHashMap, Hashtable等)都可以用以下的方式去遍历。
方法一(在for循环中使用entries实现Map的遍历):
public class MapReader {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("姓名", "张三");
map.put("编号", "CK001860");
map.put("部门", "信息管理部");
map.put("职务", "项目经理");
map.put("入职日期", "2022年9月13日");
System.out.println("方法一(在for循环中使用entries实现Map的遍历):");
Set<Map.Entry<String, String>> keys = map.entrySet();
for(Map.Entry<String, String> entry : keys){
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + ":" + value);
}
}
}
效果如下图1所示:
方法二(在for循环中遍历key或者values,一般适用于只需要map中的key或者value时使用,在性能上比使用entrySet较好):
public class MapReader {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("姓名", "张三");
map.put("编号", "CK001860");
map.put("部门", "信息管理部");
map.put("职务", "项目经理");
map.put("入职日期", "2022年9月13日");
System.out.println("方法二(在for循环中遍历key或者values,一般适用于只需要map中的key或者value时使用,在性能上比使用entrySet较好):");
// 此处输出Map的key
for(String key : map.keySet()){
System.out.print(key + "\t");
}
System.out.println();
// 此处输出Map的value
for(String value : map.values()){
System.out.print(value + "\t");
}
}
}
效果如下图2所示:
方法三(通过Iterator遍历):
public class MapReader {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("姓名", "张三");
map.put("编号", "CK001860");
map.put("部门", "信息管理部");
map.put("职务", "项目经理");
map.put("入职日期", "2022年9月13日");
System.out.println("方法三(通过Iterator遍历):");
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + ":" + value);
}
}
}
效果如下图3所示:
方法四(通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作):
public class MapReader {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("姓名", "张三");
map.put("编号", "CK001860");
map.put("部门", "信息管理部");
map.put("职务", "项目经理");
map.put("入职日期", "2022年9月13日");
System.out.println("方法四(通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作):");
for (String key : map.keySet()) {
String value = map.get(key);
System.out.println(key + ":" + value);
}
}
}
效果如下图4所示: