Write a Java program to associate the specified value with the specified key in a Tree Map


This Java code defines a class named Specified_KeyValue which contains a main method that creates a TreeMap object named stu and adds ten key-value pairs to it. The keys are integers and the values are strings representing the names of students. The keys are inserted in ascending order from 10 to 100 with a step of 10.

The code then iterates over the entries of the TreeMap using a for-each loop and prints each key-value pair to the console. The Map.Entry interface is used to represent each entry, which consists of a key and a value. The getKey() method is called to retrieve the key and the getValue() method is called to retrieve the value, and both are concatenated into a string with a comma separator.

This code demonstrates the use of a TreeMap to store key-value pairs in ascending order based on the keys. The entrySet() method is used to obtain a set view of the key-value pairs contained in the map, which is then iterated over using a for-each loop.

Source Code

import java.util.*;  
public class Specified_KeyValue
{  
	public static void main(String args[])
	{
		TreeMap<Integer,String> stu = new TreeMap<Integer,String>();		
		stu.put(10, "John");
		stu.put(20, "Joes");
		stu.put(30, "Smith");
		stu.put(40, "Charles");
		stu.put(50, "George");
		stu.put(60, "Kevin");
		stu.put(70, "Aryan");
		stu.put(80, "Dhruv");
		stu.put(90, "Clark");
		stu.put(100, "Aarav");
 
		for (Map.Entry<Integer,String> entry : stu.entrySet())
		{
			System.out.println(entry.getKey() + " , " + entry.getValue());
		}
	}
}

Output

10 , John
20 , Joes
30 , Smith
40 , Charles
50 , George
60 , Kevin
70 , Aryan
80 , Dhruv
90 , Clark
100 , Aarav

Example Programs