遍历方式
使用迭代器
Map<Integer, Object> map = new HashMap<>();
map.put(1, "hello");
map.put(2, "world");
map.put(3, "yeyeye");
//迭代器方式遍历集合
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Object object = iterator.next();
System.out.println(object);
}
下面展示的就是迭代内部类的实现,可以看到Map的迭代器并没有使用Iteraotr接口而是自己实现了一个迭代内部类。
增强for循环
通过keySet方法得到key,然后根据key获取value。
Map<Integer, Object> map = new HashMap<>();
Map<Integer, Object> map = new HashMap<>();
map.put(1, "hello");
map.put(2, "world");
map.put(3, "yeyeye");
//键值对遍历,根据键获取值
for (Integer key : map.keySet()) {
Object object = map.get(key);
System.out.println(key + ":" + object);
}
根据Entry遍历
Entry是一个键值对对象,就是说将键和值封装成了一个对象,这样我们可以从这个对象中得到键和值。从下图中可以看到,可以通过getKey和getValue去获得键和值。
Map<Integer, Object> map = new HashMap<>();
map.put(1, "hello");
map.put(2, "world");
map.put(3, "yeyeye");
//根据entry遍历
for(Map.Entry<Integer, Object> entry : map.entrySet()) {
Integer key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + ":" + value);
}