How to Iterate Sorted Keys in a TreeMap in Java


In this example, let’s  see how to reverse sorted keys in a TreeMap in Java.

Source Code

package com.beginner.examples;

import java.util.Map;
import java.util.TreeMap;

public class ReverseKeysTreeMap {

	public static void main(String[] args) {
		//Create TreeMap Object
		TreeMap treeMap = new TreeMap();
		treeMap.put(1, "Alice");
		treeMap.put(2, "Bob");
		treeMap.put(3, "Jack");
		
		System.out.println("TreeMap contains:" + treeMap);	
		
		/*
		 * Use the method descendingMap() to reverse the Map object.
		 */
		Map newMap = treeMap.descendingMap();
		System.out.println("newMap contains:" + newMap);
	}

}

Output:

TreeMap contains:{1=Alice, 2=Bob, 3=Jack}
newMap contains:{3=Jack, 2=Bob, 1=Alice}

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments