The JDK Map interface is pretty difficult to iterate as Iteration to be done on EntrySet or over the KeySet objects. MapIterator provides simple iteration over Map. Following example illustrates the same.

    Example of MapIterator Interface

    MapIteratorTester.java

    1. import org.apache.commons.collections4.IterableMap;
    2. import org.apache.commons.collections4.MapIterator;
    3. import org.apache.commons.collections4.map.HashedMap;
    4.  
    5. public class MapIteratorTester {
    6. public static void main(String[] args) {
    7. IterableMap<String, String> map = new HashedMap<>();
    8.  
    9. map.put("1", "One");
    10. map.put("2", "Two");
    11. map.put("3", "Three");
    12. map.put("4", "Four");
    13. map.put("5", "Five");
    14.  
    15. MapIterator<String, String> iterator = map.mapIterator();
    16. while (iterator.hasNext()) {
    17. Object key = iterator.next();
    18. Object value = iterator.getValue();
    19.  
    20. System.out.println("key: " + key);
    21. System.out.println("Value: " + value);
    22.  
    23. iterator.setValue(value + "_");
    24. }
    25.  
    26. System.out.println(map);
    27. }
    28. }

    Output

    It will print the following result.

    1. key: 3
    2. Value: Three
    3. key: 5
    4. Value: Five
    5. key: 2
    6. Value: Two
    7. key: 4
    8. Value: Four
    9. key: 1
    10. Value: One
    11. {3=Three_, 5=Five_, 2=Two_, 4=Four_, 1=One_}