HashMap Sort Get Java

HashMap Sort Get Java

Three programs are given on HashMap with different functionalities used very often in coding.

  1. HashMap General: In this program, API and the general operations like adding, retrieving and deleting elements, size and checking the existence of elements are done.
  2. HashMap Iteration: The iteration styles of elements, adding elements of one HashMap to another and cloning are shown.
  3. HashMap Sort: Sorting operations on keys and values are done. Special attention is paid to retrieve the key when a value is given.

Note: It is advised to read the tutorial on HashMap before attempting the above programs as it gives the knowledge on features, methods and super classes of HashMap etc.

It is the third program of the above three.

Example on HashMap Sort

HashMap Sort
Output Screen of HashMap Sort Get Java

A non-generic HashMap object hm1 is created and added a few key/value pairs with put() method.

There are two operations in HashMap, printing the keys and values in sorted ordered manner. For this keySet() and values() methods are used that return only keys and only values stored in HashMap. The keySet() returns an object of Set which does not accept duplicate elements. The Set object mySet is passed to the constructor of TreeSet and TreeSet nature is to print the elements in ascending order by default.

The same earlier technique is used to the print the values in ascending order. The values() method returns an object of Collection myCol and is passed to TreeSet constructor ts2 and ts2 is printed. The values are printed in ascending order by default.

By supplying the key to get() method, we retrieve the value associated. But the reverse is not available with Map interface; that is, when value is supplied to get the key. For this, a small code is required to write. The earlier keySet object contains all the keys of HashMap hm1. For each operation, check the value associated with a particular key and if the value matches with our required value, then return the key. The required value 10 is passed to equals() as parameter.

Leave a Reply

Your email address will not be published. Required fields are marked *