iterate treemap in java

Let’s learn iterate treemap in java.

iterate treemap in java

We cannot iterate TreeMap using iterators since TreeMap is not a collection. To iterate use entrySet() method of TreeMap class.

entrySet() method returns a Set view of the mappings contained in this map. We can iterate over key-value pair using getKey() method and getValue() method of Map.Entry.

The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. Let’s see how to iterate treemap in java example.

import java.util.Map;
import java.util.TreeMap;
public class IterateTreeMap
{
   public static void main(String[] args)
   {
      Map<String, String> tm = new TreeMap<String, String>();
      tm.put("Audi", "Audi A8 L");
      tm.put("BMW", "BMW 5 Series");
      tm.put("Mercedes-Benz", "Mercedes-Benz V-Class");
      tm.put("Bugatti", "Bugatti Chiron");
      // using for-each loop iterate over TreeMap using entrySet() method
      for(Map.Entry<String, String> entry : tm.entrySet())
         System.out.println("[" + entry.getKey() + ", " + entry.getValue() + "]");
   }
}


Output:

[Audi, Audi A8 L]
[BMW, BMW 5 Series]
[Bugatti, Bugatti Chiron]
[Mercedes-Benz, Mercedes-Benz V-Class]


Also read – variables in java