1import java.util.Map;
2import java.util.TreeMap;
3public class TreeMapExample
4{
5 public static void main(String[] args)
6 {
7 TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
8 tm.put(1000, "Apple");
9 tm.put(1002, "Raspberry");
10 tm.put(1001, "Velvet apple");
11 tm.put(1003, "Banana");
12 for(Map.Entry obj : tm.entrySet())
13 {
14 System.out.println(obj.getKey() + " " + obj.getValue());
15 }
16 }
17}
1import java.util.*;
2
3// Declare the variable using the interface of the object for flexibility.
4// Non-primative data types only.
5Map<Integer, String> mambo = new TreeMap<Integer, String>();
6
7mambo.put(key, value);
8// TreeMap will be sorted by key.
9// Work with any comparable object as a key.
10
11mambo.put(1, "Monica");
12mambo.put(2, "Erica");
13mambo.put(3, "Rita");
1- TreeMap doesn't have null key and keys are sorted
2 Can contain only unique keys and keys are sorted in ascending order.
3
1TreeSet: Can contain only unique values and it is sorted in ascending order
2TreeMap: Can contain only unique keys and keys are sorted in ascending order.
3