方法一:这种方法对键值都需要时采用这种方法,遍历用的foreach
Map<String, Object> map = new HashMap<>();
map.put("a", "aa");
map.put("b", "bb");
map.put("c", "cc");
map.put("d", "dd");
for(Map.Entry<String, Object> mapp:map.entrySet()){
// if(mapp.getKey().equals("a")){可以修改删除键值对
// mapp.setValue("abc");
// }
System.out.println(mapp.getKey() + " " + mapp.getValue());
}
方法二:这种方法用迭代器方式遍历(第一种与第二种方法都按照entry集合迭代)
Map<String, Object> map = new HashMap<>();
map.put("a", "aa");
map.put("b", "bb");
map.put("c", "cc");
map.put("d", "dd");
Set set = map.entrySet();
Iterator<Map.Entry<String, Object>> iterator = set.iterator();
while(iterator.hasNext()){
Map.Entry<String, Object> mapp = iterator.next();
System.out.println(mapp.getKey() + " " + mapp.getValue());
}
方法三:这种方法是按照key的集合迭代,这种效率较低,每次想获得值都用通过map再次获取
Map<String, Object> map = new HashMap<>();
map.put("a", "aa");
map.put("b", "bb");
map.put("c", "cc");
map.put("d", "dd");
Set set = map.keySet();
Iterator<String> iterator = set.iterator();
while(iterator.hasNext()){
String s = iterator.next();
System.out.println(s + " " + map.get(s));
}