traversing treemap in java

http‮//:s‬www.lautturi.com
traversing treemap in java

To traverse a TreeMap in Java, you can use one of the following approaches:

  1. Iterating over the key-value pairs:
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.

  1. Using the 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.

Created Time:2017-10-17 20:18:57  Author:lautturi