SortedMapmap = new TreeMap<>(); map.put("John", 23); map.put("Mike", 45); map.put("Frank", 33); map.put("David", 31); String lastKey = map.lastKey(); //returns "Mike"
SortedMapIn this example, we create a TreeMap with a reverse comparator, so the keys are sorted in reverse order. We add key-value pairs to it and call the lastKey() method to get the last key in the sorted map, which is 1. Package Library: java.utilmap = new TreeMap<>(Comparator.reverseOrder()); map.put(2, "John"); map.put(4, "Mike"); map.put(1, "Frank"); map.put(3, "David"); Integer lastKey = map.lastKey(); //returns 1