(1)先获得Map集合中所有的键,遍历键的集合,去挨个获取键对应的值
public class Example {
public static void main(String[] args) {
Map map= new HashMap();
map.put("一","Jack");
map.put("二","Rose");
map.put("三","Lucy");
Set keyset=map.keySet();//获得所有键
Iterator it = keyset.iterator();
while (it.hasNext()) {
//遍历每一个键,由键获得值
Object key = it.next();
Object value = map.get(key);
System.out.println(key+":"+value);
}
}
}
(2)先获取Map集合中的所有键值对,再遍历每一个键值对,从键值对中分别得出键和值。
public class Example {
public static void main(String[] args) {
Map map= new HashMap();
map.put("一","Jack");
map.put("二","Rose");
map.put("三","Lucy");
Set entryset=map.entrySet();//获得所有键-值对
Iterator it = entryset.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
(3)通过values方法获取Map集合中的所有值的集合
public class Example {
public static void main(String[] args) {
Map map= new HashMap();
map.put("一","Jack");
map.put("二","Rose");
map.put("三","Lucy");
map.put("四","Tom");
Collection values =map.values();
Iterator it = values.iterator();
while (it.hasNext()) {
Object value = it.next();
System.out.println(value);
}
}
}