Java TreeMap.descendingKeySet() example

Java TreeMap.descendingKeySet() example

By technicalkeeda, Views 426, Date 21-Feb-2018

In this java tutorial, You will learn how to use descendingKeySet() method of TreeMap class.The descendingKeySet() method is used to return a reverse order NavigableSet view of the keys contained in this map. The set's iterator returns the keys in descending order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

tags Java

Returns a reverse order NavigableSet view of the keys contained in this map.

syntax

public NavigableSet<K> descendingKeySet()

Returns

A reverse order navigable set view of the keys in this map.

Java TreeMap descendingKeySet() example

  • Create TreeMap instance new TreeMap < Integer, String > ();
  • Add few elements in TreeMap e.g. students.put(1, "Pooja");
  • Print the TreeMap values.
  • students.descendingKeySet(); It will returns a reverse order NavigableSet view of the keys contained in this map.
  • Print reversed key values e.g. [4, 3, 2, 1]
package com.technicalkeeda;

import java.util.NavigableSet;
import java.util.TreeMap;

public class App {
    public static void main(String args[]) {

        TreeMap < Integer, String > students = new TreeMap < Integer, String > ();

        students.put(1, "Pooja");
        students.put(2, "Ajit");
        students.put(3, "Yashwant");
        students.put(4, "Aditi");

        System.out.println("TreeMap values :- " + students);

        NavigableSet nevigableSet = students.descendingKeySet();

        System.out.println("Reverse key values:- " + nevigableSet);

    }
}

output

TreeMap values :- {1=Pooja, 2=Ajit, 3=Yashwant, 4=Aditi}
Reverse key values:- [4, 3, 2, 1]
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]