Menu
Topics Index
...
`

TreeMapUsingComparator - Java Example Program


TreeMapUsingComparator
import java.util.*;

class TreeMapUsingComparator
{
    TreeMap descendingorder = new TreeMap<>(new Comparator<Integer>()//LINE A
    {
    
        public int compare(Integer first, Integer second)
        {
            return second.compareTo(first);//LINE B
        }
    });
    descendingorder.put(1, "first");
    descendingorder.put(0, "zero");
    descendingorder.put(3, "third");
    descendingorder.put(5, "five");
    descendingorder.put(4, "four"); // LINE C
    System.out.println("Map sorted according to the comparator : " + descendingorder);
}
OUTPUT

Map sorted according to the comparator : {5=five, 4=four, 3=third, 1=first, 0=zero}

DESCRIPTION

In the above program at LINE A we used a Comparator that sorts the TreeMap in descending order.

THINGS TO TRY
  • In the above program interchange first and second so that the map is printed in ascending order.
  • Include the following code after LINE C.
    descendingorder.put(4, "four");
    The entry will get included in the output.

© meritcampus 2019

All Rights Reserved.

Open In App