Write a Java program to get all keys from the given a Tree Map


This Java code defines a class named GetAll_Keys which contains a main method that creates a TreeMap object named s1 and adds five key-value pairs to it. The keys are integers and the values are strings representing the names of individuals.

The code then prints a message to the console indicating that it will be retrieving all keys from the map. To retrieve all the keys from the TreeMap, the keySet() method of the TreeMap class is used to obtain a set view of the keys contained in the map. The keySet() method returns a Set object containing all the keys in the map.

The code then uses a for-each loop to iterate through the set of keys and print each key to the console. This code demonstrates how to retrieve all the keys from a TreeMap using the keySet() method.

Source Code

import java.util.*;  
public class GetAll_Keys
{
	public static void main(String args[])
	{
		TreeMap<Integer,String> s1 = new TreeMap<Integer,String>();		
		s1.put(101, "John");
		s1.put(102, "Joes");
		s1.put(103, "Smith");
		s1.put(104, "Charles");
		s1.put(105, "George");
		System.out.println("All Keys from the given a TreeMap..");
 
		Set<Integer> keys = s1.keySet();
		for(Integer key: keys)
		{
			System.out.println(key);
		}
	}
}

Output

All Keys from the given a TreeMap..
101
102
103
104
105

Example Programs