Pages

Friday, January 22, 2021

How To Iterate or Traverse TreeMap In Reverse Order in Java?

1. Overview

In this tutorial, We will learn how to traverse and print the values of the TreeMap in the reverse order in java?

By default, TreeMap sorts the objects added to it in ascending order. But, now we want to print the values are in reverse order that means in the descending order. 

In the previous article, we have seen how to traverse TreeMap in natural order in java 8?

This can be done using the following in 3 ways.

1) Collections.reverseOrder()
2) TreeMap.descendingkeySet()
3) TreeMap.descendingMap()

How To Iterate or Traverse TreaMap In Reverse Order in Java?


2. TreeMap Reverse Traverse - Collections.reverseOrder()


First, let us learn the simple and easy one to understand the reversing and accessing the values from TreeMap.

When we create the TreeMap object, we just need to pass the Collections.reverseOrder() to the TreeMap constructor. Collections.reverseOrder() method indicates to TreeMap sort the keys based on the reverse order that is descending order.

The below example is based on the Collections.reverseOrder() method.

package com.javaprogramto.collections.treemap;

import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapReverseTraversalExample {

	public static void main(String[] args) {
		
		// Creating the TreeMap object with reverse comparator using Collections.reverseOrder()
		Map<String, Integer> studentsCountMap = new TreeMap<>(Collections.reverseOrder());
		
		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);
		
		// Getting the Set object using keySet() method which returns the keys in the reverse order
		Set<String> keysSet = studentsCountMap.keySet();
		
		// Getting the iterator object
		Iterator<String > it = keysSet.iterator();
		
		// Iterating the map using regular method of iterator which retrieves the values in the reverse order.
		while (it.hasNext()) {
			String key = it.next();
			System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key));
		}
	}
}

Output:

See how the order of the output is printed in the reverse order.

Key - 5nd class, Value - 500
Key - 4nd class, Value - 400
Key - 3nd class, Value - 300
Key - 2nd class, Value - 200
Key - 1nd class, Value - 100

3. TreeMap Reverse Traverse - Collections. descendingkeySet()


The above method works only when we have control over creating the TreeMap instance otherwise need to follow the new method as below.

There are some scenarios where the TreeMap is created by another api or library that TreeMap object you are getting into your code.

In such cases, TreeMap has another method descendingkeySet() to get the keys in the descending order which is contrary to the natural order.

But, First need to get the keys in descending order and next get the value from map again with get() method.
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapReversedescendingkeySetExample {

	public static void main(String[] args) {
		
		// Creating the TreeMap object with default constructor
		TreeMap<String, Integer> studentsCountMap = new TreeMap<>();
		
		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);
		
		// Getting all keys as Set object using descendingKeySet()
		Set<String> keysSet = studentsCountMap.descendingKeySet();
		
		// Getting the iterator object
		Iterator<String > it = keysSet.iterator();
		
		// Iterating the map using regular method of iterator which retrieves the values in the reverse order.
		while (it.hasNext()) {
			String key = it.next();
			System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key));
		}
	}
}

Output:
Key - 5nd class, Value - 500
Key - 4nd class, Value - 400
Key - 3nd class, Value - 300
Key - 2nd class, Value - 200
Key - 1nd class, Value - 100

4. TreeMap Reverse Traverse - Collections. descendingMap()


Finally, TreeMap has another useful method to get the Map in descending order with descendingMap().

Next, iterate returned map with java 8 forEach() method to print the key-values

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

public class TreeMapReversedescendingkeymapExample {

	public static void main(String[] args) {

		// Creating the TreeMap object with default constructor
		TreeMap<String, Integer> studentsCountMap = new TreeMap<>();

		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);

		// Getting all keys as Set object using descendingKeySet()
		Map<String, Integer> map = studentsCountMap.descendingMap();

		map.forEach((key, value) -> System.out.println("Key - " + key + ", Value - " + value));
	}
}

5. Conclusion


In this article, we have explored the different ways to traverse the TreeMap in the reverse order.


No comments:

Post a Comment

Please do not add any spam links in the comments section.