Iterate or loop over each entry in map

This example will show how to loop over each entry in a map.

EntrySet

In this snippet we will use a for each loop to iterate through each entry returned by the Maps.entrySet then logging the Map.key and the Map.value.

@Test
public void iterate_or_loop_over_a_map_entryset () {
    
    Map<Integer, String> numbers = new HashMap<Integer, String>();
    numbers.put(new Integer(1), "one");
    numbers.put(new Integer(2), "two");

    for (Map.Entry<Integer, String> entry : numbers.entrySet()) {
        logger.info("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }

}

Iterator

In this snippet we use an Iterator to loop over each Map.entrySet. The Map.entrySet will return an entry which will contain the key and value information.

@Test
public void iterate_or_loop_over_a_map_iterator () {
    
    Map<Integer, String> numbers = new HashMap<Integer, String>();
    numbers.put(new Integer(1), "one");
    numbers.put(new Integer(2), "two");

    Iterator<Map.Entry<Integer, String>> it = numbers.entrySet().iterator();
    while (it.hasNext()) {
        Entry<Integer, String> mapping = it.next();
        
        Integer key = mapping.getKey();
        String value = mapping.getValue();
        
        logger.info("Key : " + key + " Value : " + value);
    }
}