OrderedMap is a new interface for maps to retain the order in which elements are added. LinkedMap and ListOrderedMap are two available implementations. This interfaces supports iterator that of Map and allows iteration in both direction either forwards or backwards in a Map. Following example illustrates the same.

    Example of MapIterator Interface

    OrderedMapTester.java

    1. import org.apache.commons.collections4.OrderedMap;
    2. import org.apache.commons.collections4.map.LinkedMap;
    3.  
    4. public class OrderedMapTester {
    5. public static void main(String[] args) {
    6. OrderedMap<String, String> map = new LinkedMap<String, String>();
    7. map.put("One", "1");
    8. map.put("Two", "2");
    9. map.put("Three", "3");
    10.  
    11. System.out.println(map.firstKey());
    12. System.out.println(map.nextKey("One"));
    13. System.out.println(map.nextKey("Two"));
    14. }
    15. }

    Output

    It will print the following result.

    1. One
    2. Two
    3. Three