1、先取出所有key,通过key取出对应的value
public class Map_1 {
@SuppressWarnings({"all"})
public static void main(String[] args) {
HashMap map = new HashMap();
map.put("No1","张三");
map.put("No2","李四");
map.put("No3","王五");
map.put("No4","周六");
//取出key
Set set = map.keySet();
//增强for
for (Object key : set) {
System.out.println(key+"-"+map.get(key));
}
//迭代器
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
System.out.println(key+"-"+map.get(key));
}
}
}
2、取出所有的values
//取出所有的value
Collection values = map.values();
//增强for
for (Object value : values) {
System.out.println(value);
}
//迭代器
Iterator iterator1 = values.iterator();
while (iterator1.hasNext()) {
Object value = iterator1.next();
System.out.println(value);
}
3、通过EntrySet获取key-value
Set entrySet = map.entrySet();
//增强for
for (Object entry : entrySet) {
//将entry转成Map.entry
Map.Entry m = (Map.Entry)entry;
System.out.println(m.getKey()+"-"+m.getValue());
}
//迭代器
Iterator iterator2 = entrySet.iterator();
while (iterator2.hasNext()) {
Object keyValue = iterator2.next();
//向下转型Map.Entry
Map.Entry m = (Map.Entry)keyValue;
System.out.println(m.getKey()+"-"+m.getValue());
}