import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; public class Java8Template {
public static void main(String[] args) {
Map<String,Integer>items=new HashMap<>();
items.put("A",10);
items.put("B",20);
items.put("C",30);
items.put("D",40);
items.put("E",50);
items.put("F",60); //1.使用entrySet的迭代器
Iterator iter1=items.entrySet().iterator();
while(iter1.hasNext()){
Map.Entry<String,Integer> entry=(Map.Entry<String,Integer>)iter1.next();
System.out.println("Item :"+entry.getKey()+" Count:"+entry.getValue()); } //2.使用keySet的迭代器
Iterator iter2=items.keySet().iterator();
while(iter2.hasNext()){
String key=(String) iter2.next();
System.out.println("Item :"+key+" Count:"+items.get(key));
} //3.使用for循环利用EntrySet进行遍历
for(Map.Entry<String,Integer>entry:items.entrySet()){
System.out.println("Item :"+entry.getKey()+" Count:"+entry.getValue());
} //4.使用for循环利用keySet进行遍历
for (String key:items.keySet()){
System.out.println("Item :"+key+" Count:"+items.get(key));
} //5.java8中使用forEach进行遍历
items.forEach((k,v)-> System.out.println("Item :"+k+" Count:"+v)); }
}
其中第五种采用了Java8中的lambda表达式进行遍历。