1.拿到所有键,放入set集合,遍历取键,用get方法取值。
public void test1() {
HashMap<Integer, String> map = new HashMap<>();
map.put(1,"奥");
map.put(2,"运");
map.put(3,"会");
Set<Integer> set = map.keySet();
for (Integer i: set) {
System.out.println(integer+"="+map.get(i));
}
}
2.获取键值对集合(entry集合),遍历集合,用Entry中的getKey()和getValue()方法获取键和值。
public void test2() {
map<Integer, String> map= new HashMap<>();
map.put(1,"奥");
map.put(2,"运");
map.put(3,"会");
Set<Map.Entry<Integer, String>> entries = map.entrySet();
for (Map.Entry<Integer, String> entry : entries) {
Integer key = entry.getKey();
String value = entry.getValue();
System.out.println(key+" "+value);
}
}