Pages

Sunday, April 5, 2020

TreeMap in Java with Examples (Sorting Ascending or Descending or Reverse order)

1. Introduction


In this article, We'll learn how to use TreemMap in java. It is a Red-Black tree based NavigableMap implementation.  TreeMap extends AbstractMap and implements NavigableMap. The main difference between them is that HashMap is an unordered collection while TreeMap is sorted in the ascending order of its keys. TreeMap is an unsynchronized collection class which means it is not suitable for thread-safe operations until unless synchronized explicitly.

TreeMap is mainly used to sort the keys in ascending order or descending order.

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable

TreeMap in Java with Example (ascending or descending or reverse order)




2. TreeMap Example to Sort the keys


By default, TreeMap does sorting in ascending order.

package com.java.w3schools.blog.treemap;

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

public class TreeMapExamples {

 public static void main(String[] args) {
 
// sorting in ascending order
Map<Integer, String> treeMap = new TreeMap<>(); treeMap.put(300, "Three Hundred"); treeMap.put(400, "Four Hundred"); treeMap.put(100, "One Hundred"); treeMap.put(200, "Two Hundred"); System.out.println("sorted treemap : " + treeMap); } }

Output:

sorted treemap : {100=One Hundred, 200=Two Hundred, 300=Three Hundred, 400=Four Hundred}

Added keys in the random order but the output is sorted and printed in order.


3. TreeMap in Descending order or reverse order


To print the treemap in descending order, the comparator needs to be passed to the TreeMap constructor as Collections.reverseOrder().

Collections.reverseOrder() generates the Compartor implementation to reverse the elements.


  //sorting in reverse or descending order
Output:

Desending order of treemap : {400=400.0, 300=300.0, 200=200.0, 100=100.0}

4. Conclusion


In this article, We have seen that TreeMap is used to sort based on the keys in ascending and reverse order.

GitHub

TreeMap API

HashMap API

No comments:

Post a Comment

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