|
| 1 | +import java.util.Comparator; |
| 2 | +import java.util.SortedMap; |
| 3 | +import java.util.TreeMap; |
| 4 | + |
| 5 | +class TreeMap_Implementation { |
| 6 | + |
| 7 | + |
| 8 | + //A TreeMap is a map implementation where they are always sorted based on the natural ordering of the keys, |
| 9 | + // or based on a custom Comparator that you can provide at the time of creation of the TreeMap. |
| 10 | + |
| 11 | + // |
| 12 | + public static void main(String[] args) { |
| 13 | + // Creating a TreeMap |
| 14 | + SortedMap<String, String> names = new TreeMap<>(); |
| 15 | + |
| 16 | + |
| 17 | + // Adding new key-value pairs to a TreeMap |
| 18 | + names.put("Aanchal", "girl"); |
| 19 | + names.put("Rahul", "boy"); |
| 20 | + names.put("Arjun", "boy"); |
| 21 | + names.put("Karen", "girl"); |
| 22 | + names.put("Salman", "boy"); |
| 23 | + |
| 24 | + // Printing the TreeMap (Output will be sorted based on keys) |
| 25 | + System.out.println(names); |
| 26 | + |
| 27 | + System.out.println(((TreeMap<String, String>) names).firstEntry()); |
| 28 | + |
| 29 | + System.out.print(((TreeMap<String, String>) names).lastEntry()); |
| 30 | + |
| 31 | + |
| 32 | + SortedMap<String, String> names_2 = new TreeMap<>(new Comparator<String>() { |
| 33 | + @Override |
| 34 | + public int compare(String s1, String s2) { |
| 35 | + return s2.compareTo(s1); |
| 36 | + } |
| 37 | + }); |
| 38 | + |
| 39 | + // Adding new key-value pairs to a TreeMap |
| 40 | + names_2.put("Aanchal", "girl"); |
| 41 | + names_2.put("Rahul", "boy"); |
| 42 | + names_2.put("Arjun", "boy"); |
| 43 | + names_2.put("Karen", "girl"); |
| 44 | + names_2.put("Salman", "boy"); |
| 45 | + |
| 46 | + // Printing the TreeMap (The keys will be sorted based on the supplied comparator in descending order.) |
| 47 | + System.out.println(names_2); |
| 48 | + |
| 49 | + System.out.println(((TreeMap<String, String>) names_2).firstEntry()); |
| 50 | + |
| 51 | + System.out.print(((TreeMap<String, String>) names_2).lastEntry()); |
| 52 | + } |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | + |
| 57 | + /* Output: |
| 58 | + {Aanchal=girl, Arjun=boy, Karen=girl, Rahul=boy, Salman=boy} |
| 59 | + Aanchal=girl |
| 60 | + Salman=boy{Salman=boy, Rahul=boy, Karen=girl, Arjun=boy, Aanchal=girl} |
| 61 | + Salman=boy |
| 62 | + Aanchal=girl*/ |
0 commit comments