场景:Java遍历Map方式
1.常见遍历方式
public static void mode1() {
Map<String, String> map = new HashMap<String, String>();
map.put("浙江", "杭州");
map.put("江苏", "苏州");
map.put("福建", "福州");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key=" + entry.getKey() + ",Value=" + entry.getValue());
}
}
2.遍历key和value
public static void mode2() {
Map<String, String> map = new HashMap<String, String>();
map.put("浙江", "杭州");
map.put("江苏", "苏州");
map.put("福建", "福州");
for (String key : map.keySet()) {
System.out.println("Key=" + key);
}
for (String value : map.values()) {
System.out.println("Value=" + value);
}
}
3.使用Iterator遍历
public static void mode3() {
Map<String, String> map = new HashMap<String, String>();
map.put("浙江", "杭州");
map.put("江苏", "苏州");
map.put("福建", "福州");
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
System.out.println("Key=" + entry.getKey() + ",Value=" + entry.getValue());
}
}
4.使用使用key获取值
public static void mode4() {
Map<String, String> map = new HashMap<String, String>();
map.put("浙江", "杭州");
map.put("江苏", "苏州");
map.put("福建", "福州");
for (String key : map.keySet()) {
String value = map.get(key);
System.out.println("Key=" + key + ",Value=" + value);
}
}
5.测试main函数
public static void main(String[] args) {
System.out.println("测试开始......");
System.out.println("方式一:");
mode1();
System.out.println("方式二:");
mode2();
System.out.println("方式三:");
mode3();
System.out.println("方式四:");
mode4();
System.out.println("测试结束......");
}
6.测试结果
测试开始......
方式一:
Key=浙江,Value=杭州
Key=江苏,Value=苏州
Key=福建,Value=福州
方式二:
Key=浙江
Key=江苏
Key=福建
Value=杭州
Value=苏州
Value=福州
方式三:
Key=浙江,Value=杭州
Key=江苏,Value=苏州
Key=福建,Value=福州
方式四:
Key=浙江,Value=杭州
Key=江苏,Value=苏州
Key=福建,Value=福州
测试结束......
以上,TKS.