好长时间没写用map了,今天写,突然发现不会用了。于是有了下面的练习
public class TestMap {
public static void main(String args[]){
Map<String,Integer> myMap = new HashMap<String,Integer>();
myMap.put("a", 1);
myMap.put("b", 12);
myMap.put("c", 123);
myMap.put("d", 1234);
myMap.put("e", 12345);
myMap.put("f", 123456);
//使用entrySet进行遍历
Iterator<Map.Entry<String, Integer>> it1 = myMap.entrySet().iterator();
while(it1.hasNext()){
Map.Entry<String, Integer> entrySet = it1.next();
System.out.println("Key = " + entrySet.getKey() + "; Value = " + entrySet.getValue());
}
//使用keySet进行遍历
Iterator<String> it2 = myMap.keySet().iterator();
while(it2.hasNext()){
String key = it2.next();
System.out.println("Key = " + key + "; Value = " + myMap.get(key));
}
//使用collections工具类进行便利:此处得到的是value的遍历
Collection<Integer> c1 = myMap.values();
Iterator<Integer> it3 = c1.iterator();
while(it3.hasNext()){
System.out.println(it3.next());
}
//使用collections工具类进行便利:此处得到的是key的遍历
Collection<String> c2 = myMap.keySet();
Iterator<String> it4 = c2.iterator();
while(it4.hasNext()){
System.out.println(it4.next());
}
}
}