Map 的遍历有三种方法:
- 使用 values() 方法,该方法会返回一个Collection,通过集合的 iterator() 方法 取得集合的 迭代器 ,然后使用迭代器进行遍历所有元素。
- 组合使用 keySet() 和 get()方法 。 keySet 方法返回一个Key值的 Set集合 ,然后通过遍历集合中的key值 ,利用 get 方法依次取出Map中的所有元素 达到遍历的效果。
Set<K> | keySet() Returns a set view of the keys contained in this map. |
V | get(Object key) Returns the value to which this map maps the specified key. |
3. 使用 entrySet 方法 返回一个 Map.Entry (是键值对)的泛型集合,通过遍历集合,一次的使用 getKey 和 getValue 取出 key 和 value 达到遍历的效果。