public static void main(String[] args) {
Map<Integer,String> hashMap = new HashMap<Integer,String>();
hashMap.put(1,"a");
hashMap.put(2,"b");
hashMap.put(3,"c");
//第一种:
Set<Integer> set = hashMap.keySet(); //得到所有key的集合
for (Integer in : set){
String str = hashMap.get(in);//得到每个key对应value的值
System.out.println(in + " " + str);
}
//第二种:
Iterator<Map.Entry<Integer, String>> it = hashMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " value= " + entry.getValue());
}
//第三种:(推荐)
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第四种:(打印出所有的value)
for (String v : hashMap.values()) {
System.out.println("value= " + v);
}
}
Map<Integer,String> hashMap = new HashMap<Integer,String>();
hashMap.put(1,"a");
hashMap.put(2,"b");
hashMap.put(3,"c");
//第一种:
Set<Integer> set = hashMap.keySet(); //得到所有key的集合
for (Integer in : set){
String str = hashMap.get(in);//得到每个key对应value的值
System.out.println(in + " " + str);
}
//第二种:
Iterator<Map.Entry<Integer, String>> it = hashMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " value= " + entry.getValue());
}
//第三种:(推荐)
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第四种:(打印出所有的value)
for (String v : hashMap.values()) {
System.out.println("value= " + v);
}
}