Traverse key and value according to Map.Entry()
Set<Map.Entry<String, String>> entryseSet=map.entrySet();
for (Map.Entry<String, String> entry:entryseSet) {
System.out.println(entry.getKey()+","+entry.getValue());
}
Traverse according to KeySet to get key and value
Set<String> set = map.keySet();
for (String s:set) {
System.out.println(s+","+map.get(s));
}
Traverse according to Values, only value can be obtained
Set<String> set = map.values();
for (String s:set) {
System.out.println(s);
}
Map.getOrDefault()
Usage: Map.getOrDefault(key, default value);
One-to-one correspondence of key and value will be stored in the Map.
If there is a key in the Map, the value corresponding to the key is returned.
If the key does not exist in the Map, the default value is returned.
public class Demo {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("张三", 23);
map.put("赵四", 24);
map.put("王五", 25);
String age= map.getOrDefault("赵四", 30);
System.out.println(age);// 24,map中存在"赵四",使用其对应值24
String age = map.getOrDefault("刘能", 30);
System.out.println(age);// 30,map中不存在"刘能",使用默认值30
}
}