public void mymap(){
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "玫瑰");
map.put(2, "百合");
map.put(3, "牡丹");
map.put(4, "月季");
//map的entrySet方法遍历,返回的Set
Set<Entry<Integer,String>> set = map.entrySet();
for(Entry<Integer,String> en:set){
Integer in = en.getKey();
String st = en.getValue();
System.out.println(in+"====="+st);
}
//利用map.entrySet().iterator()进行遍历,返回一个Iterator对象
Iterator<Entry<Integer,String>> iter = map.entrySet().iterator();
while(iter.hasNext()){
Entry<Integer,String> ent = iter.next();
Integer key = ent.getKey();
String value = ent.getValue();
System.out.println(key+"=========="+value);
}
//只获取map的键,调用map的keySet()
for(Integer in:map.keySet()){
System.out.println(in);
}
//获取map的值,调用map的values()
for(String st:map.values()){
System.out.println(st);
}
转载于:https://www.cnblogs.com/cl1025/p/8981373.html