Commons Collections 简明教程

Commons Collections - MapIterator Interface

JDK Map 接口很难迭代,因为迭代必须在 EntrySet 或 KeySet 对象上进行。MapIterator 在 Map 上提供简单的迭代。以下示例对此进行了说明。

Example of MapIterator Interface

MapIteratorTester.java 的示例如下 −

import org.apache.commons.collections4.IterableMap;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.map.HashedMap;

public class MapIteratorTester {
   public static void main(String[] args) {
      IterableMap<String, String> map = new HashedMap<>();

      map.put("1", "One");
      map.put("2", "Two");
      map.put("3", "Three");
      map.put("4", "Four");
      map.put("5", "Five");

      MapIterator<String, String> iterator = map.mapIterator();
      while (iterator.hasNext()) {
         Object key = iterator.next();
         Object value = iterator.getValue();

         System.out.println("key: " + key);
         System.out.println("Value: " + value);

         iterator.setValue(value + "_");
      }
      System.out.println(map);
   }
}

Output

输出如下 −

key: 3
Value: Three
key: 5
Value: Five
key: 2
Value: Two
key: 4
Value: Four
key: 1
Value: One
{3=Three_, 5=Five_, 2=Two_, 4=Four_, 1=One_}