1import java.util.SortedMap;
2import java.util.TreeMap;
3public class TreeMapHeadMapMethodExample
4{
5 public static void main(String[] args)
6 {
7 TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
8 // map string values to integer keys
9 tm.put(65, "mango");
10 tm.put(63, "apple");
11 tm.put(35, "grapes");
12 tm.put(60, "pineapple");
13 tm.put(26, "banana");
14 System.out.println("Given TreeMap is: " + tm);
15 // create SortedMap for map head
16 SortedMap<Integer, String> sm = new TreeMap<Integer, String>();
17 sm = tm.headMap(60);
18 // Getting map head
19 System.out.println("headmap is: " + sm);
20 }
21}
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