The program creates a TreeMap object named s1 and adds some key-value pairs to it. Then, it prints out a portion of the TreeMap based on the specified keys using the headMap() method.
The headMap() method returns a view of the portion of the map whose keys are strictly less than the specified key. In this program, the first headMap() method call returns all the key-value pairs whose keys are less than 101, the second headMap() method call returns all the key-value pairs whose keys are less than 103, and the third headMap() method call returns all the key-value pairs in the TreeMap since the key 107 is greater than the greatest key in the TreeMap.
import java.util.*; import java.util.Map.Entry; public class GetPortion { public static void main(String args[]) { TreeMap<Integer,String> s1 = new TreeMap<Integer,String>(); s1.put(101, "Joes"); s1.put(102, "Charles"); s1.put(103, "John"); s1.put(104, "George"); s1.put(105, "Smith"); System.out.println("Given TreeMap : " + s1); System.out.println("Checking the 101 Key(s): " + s1.headMap(101)); System.out.println("Checking the 103 Key(s): " + s1.headMap(103)); System.out.println("Checking the 107 Key(s): " + s1.headMap(107)); } }
Given TreeMap : {101=Joes, 102=Charles, 103=John, 104=George, 105=Smith} Checking the 101 Key(s): {} Checking the 103 Key(s): {101=Joes, 102=Charles} Checking the 107 Key(s): {101=Joes, 102=Charles, 103=John, 104=George, 105=Smith}
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions