This program demonstrates how to find the greatest and least key-value pairs in a TreeMap in Java. Explanation of the program:
firstEntry() method returns the first (lowest) key-value pair in the TreeMap and lastEntry() method returns the last (highest) key-value pair in the TreeMap.
import java.util.*; import java.util.Map.Entry; public class GreatestLeast_KeyValue { public static void main(String args[]) { TreeMap<Integer,String> s1 = new TreeMap<Integer,String>(); s1.put(101, "John"); s1.put(102, "Joes"); s1.put(104, "Charles"); s1.put(105, "George"); s1.put(103, "Smith"); System.out.println("Given TreeMap : " + s1); System.out.println("Greatest Key : " + s1.firstEntry()); System.out.println("Least Key : " + s1.lastEntry()); } }
Given TreeMap : {101=John, 102=Joes, 103=Smith, 104=Charles, 105=George} Greatest Key : 101=John Least Key : 105=George
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions