With TreeMaps, unlike HashMaps, the elements are already arranged in a specific order.
import java.util.TreeMap;
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
This code shows an example of how to use the TreeMap class in Java. The TreeMap class implements the Map interface and provides a tree-based implementation of the map. It stores the elements in a sorted order, based on the keys.
In this example, the TreeMap object “map” is created and four elements are added to it using the put() method. The key-value pairs are then printed using a for-each loop and the keySet() method. The values() method returns a Collection view of the values contained in the map and the keySet() method returns a Set view of the keys contained in the map.
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
map.put(10, "productA");
map.put(24, "productB");
map.put(3, "productC");
map.put(8, "productD");
map.put(44, "productF");
for(Integer key: map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
// Returns a Collection view of the values contained in this map.
System.out.println(map.values());
// Returns a Set view of the keys contained in this map.
System.out.println(map.keySet());
}
}
3: productC
8: productD
10: productA
24: productB
44: productF
[productC, productD, productA, productB, productF]
[3, 8, 10, 24, 44]