JDK Map接口很难迭代,因为迭代要在EntrySet或KeySet对象上完成. MapIterator提供了对Map的简单迭代.以下示例说明了相同的内容.
MapIterator接口示例
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) { IterableMapmap = new HashedMap<>(); map.put("1", "One"); map.put("2", "Two"); map.put("3", "Three"); map.put("4", "Four"); map.put("5", "Five"); MapIterator 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); } }
输出
它将打印以下结果.
key: 3Value: Threekey: 5Value: Fivekey: 2Value: Twokey: 4Value: Fourkey: 1Value: One{3=Three_, 5=Five_, 2=Two_, 4=Four_, 1=One_}