Map接口与Collection接口不同,Collection接口有iterator()方法,可以很方便的取得Iterator对象来输出,而Map接口本身没有此方法。
Collection接口中保存的是一个个的对象,Map集合中保存的是一对一对的键值对;在Map接口中有一个重要的方法,将Map集合转为Set集合:public Set<Map.Entry<K,V>> entrySet();
Map要想调用Iterator接口输出,需要先将Map集合转换为Set集合,获取到Iterator对象,从而进行输出。
eg:Map调用Iterator接口输出:
public class TestDemo {
public static void main(String[] args) {
Map<Integer,String> map = new HashMap<>();
map.put(1,"zs");
map.put(2,"ls");
map.put(3,"ww");
Set<Map.Entry<Integer,String>> set = map.entrySet();
Iterator<Map.Entry<Integer,String>> iterator = set.iterator();
while (iterator.hasNext()){
Map.Entry<Integer,String> entry = iterator.next();
System.out.println(entry.getKey()+"="+entry.getValue());
}
}
}