To traverse a TreeMap
in Java, you can use one of the following approaches:
TreeMap<Integer, String> map = new TreeMap<>(); // add some key-value pairs to the map map.put(1, "one"); map.put(2, "two"); map.put(3, "three"); for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); }
This will print out the key-value pairs in the map in ascending order of the keys.
keySet
method to get a Set
of the keys, and then iterating over the keys:TreeMap<Integer, String> map = new TreeMap<>(); // add some key-value pairs to the map map.put(1, "one"); map.put(2, "two"); map.put(3, "three"); for (Integer key : map.keySet()) { String value = map.get(key); System.out.println(key + ": " + value); }
This will also print out the key-value pairs in ascending order of the keys.