1example of TreeMap ceilingKey(K key) method when it returns null
2import java.util.NavigableMap;
3import java.util.TreeMap;
4public class TreeMapCeilingkeyDemo
5{
6 public static void main(String[] args)
7 {
8 NavigableMap<Integer, String> nm = new TreeMap<Integer, String>();
9 nm.put(10, "apple");
10 nm.put(20, "banana");
11 nm.put(30, "cherry");
12 nm.put(40, "fig");
13 nm.put(60, "grape");
14 nm.put(70, "kiwifruit");
15 // 200 is not present in map
16 // or any key greater than 200
17 // hence returns null
18 System.out.println("Ceiling key for 200: " + nm.ceilingKey(200));
19 }
20}
1import java.util.NavigableMap;
2import java.util.TreeMap;
3public class TreeMapCeilingkeyDemo
4{
5 public static void main(String[] args)
6 {
7 NavigableMap<Integer, String> nm = new TreeMap<Integer, String>();
8 nm.put(10, "apple");
9 nm.put(20, "banana");
10 nm.put(30, "cherry");
11 nm.put(40, "fig");
12 nm.put(60, "grape");
13 nm.put(70, "kiwifruit");
14 // 60 is least value > 50
15 // it is returned as key.
16 System.out.println("Ceiling key for 50: " + nm.ceilingKey(50));
17 }
18}
1example on TreeMap ceilingKey(K key) method when it returns ClassCastException
2import java.util.NavigableMap;
3import java.util.TreeMap;
4public class TreeMapCeilingkeyDemo
5{
6 public static void main(String[] args)
7 {
8 NavigableMap<Object, String> tm = new TreeMap<Object, String>();
9 tm.put(10, "apple");
10 tm.put(20, "banana");
11 tm.put(30, "cherry");
12 tm.put(40, "fig");
13 tm.put(60, "grape");
14 tm.put(70, "kiwifruit");
15 try
16 {
17 // returns ClassCastException
18 // we cannot compare String object with an Integer object
19 System.out.println("Ceiling key entry for \"asd\": " + tm.ceilingKey(new String("mango")));
20 }
21 catch(Exception ex)
22 {
23 System.out.println("Exception: " + ex);
24 }
25 }
26}