Map的三种遍历方式

时间:2022-10-29 15:41:37
package com.qf.day13;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class work9 {
public static void main(String[] args) {
Map<String, Object> map=new HashMap<>();
for(int i=0;i<10;i++){
map.put(""+i, i);
}
System.out.println("用Map的内部类Entry,来遍历Map集合");
Set<Entry<String, Object>> entrySet = map.entrySet();
for(Entry<String,Object> entry:entrySet){
System.out.println(entry.getKey()+"-"+entry.getValue());
}
System.out.println("利用迭代器,遍历Map集合");
Iterator<String> iterator=map.keySet().iterator();
while(iterator.hasNext()){
String id=iterator.next();
System.out.println(id+"-"+map.get(id));
}
System.out.println("遍历values");
Collection<Object> collection=map.values();
for(Object object:collection){
System.out.println(object);
}
}

}