Write a Java program to get a reverse order view of the keys contained in a given map


This program demonstrates how to get a reverse order view of the keys in a TreeMap in Java. The TreeMap is initialized with integer keys and string values, and some key-value pairs are added to it using the put() method.

Then, the program prints out the original TreeMap using System.out.println() and gets the reverse order view of the keys using the descendingKeySet() method of the TreeMap. The descendingKeySet() method returns a NavigableSet of the keys in reverse order.

Finally, the program prints out the reverse order view of the keys using System.out.println().

Source Code

import java.util.*;
import java.util.Map.Entry;  
public class Reverse_Order
{  
	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("Reverse Order View of the Keys : " + s1.descendingKeySet());
	}
}

Output

Given TreeMap : {101=Joes, 102=Charles, 103=John, 104=George, 105=Smith}
Reverse Order View of the Keys : [105, 104, 103, 102, 101]

Example Programs