Map的三種遍歷方式
阿新 • • 發佈:2018-11-10
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);
}
}
}