Sort LinkedHashMap by values using Comparable Interface in Java


LinkedHashMap is a generic class that is used to implement Map Interface. Also, it is a sub class of the HashMap class therefore, it can use all the methods and also perform similar operations that a HashMap class is capable of.

Java provides various ways to sort LinkedHashMap, we will learn how to create and sort it by its values using Comparable Interface through this article.

Program to sort LinkedHashMap by Values

Before jumping to the sorting program directly, let’s take a look at few concepts first −

LinkedHashMap

As we have discussed earlier the LinkedHashMap class extends HashMap class to implement Map Interface. It maintains Key-Value pair. The Key is an object that is used to fetch and receive value associated with it. It stores the elements of the map in LinkedList in the order in which they are inserted i.e. it maintains the insertion order of elements. Also, whenever we return its element it will be printed in the insertion order.

The general syntax for LinkedHashMap is as follows −

Syntax

LinkedHashMap< TypeOfKey, TypeOfValue > nameOfMap = new LinkedHashMap<>();

In the above syntax,

TypeOfKey − Specify the datatype of Keys.

TypeOfValue − Specify the datatype of values that are going to be stored in map.

nameOfMap − Give a suitable name to your map.

Comparable interface

Java provides a variety of sorting algorithms and methods that can help us to sort arrays, lists or any collections. The comparable interface is an additional way that is useful when we want to sort custom objects by their natural ordering. For example, It sorts strings in dictionary order and numerics in numerical order. This interface is available in ‘java.lang’ package.

Syntax

class nameOfclass implements Comparable<nameOfclass>

compareTo() method

The Comparable Interface defines only a single method named ‘CompareTo’ that can be overridden in order to sort the collection of objects. It gives the power to compare the objects of a class to itself. It returns 0 when ‘this’ object is equal to passed object, a positive value if ‘this’ object is greater otherwise a negative value.

Syntax

compareTo(nameOfclass nameOfobject); 

Collections.sort() method

The class ‘Collections’ of the Collection Interface provides a static method named ‘Collections.sort()’ that can sort elements of specified collections like ArrayList or LinkedList. It is available in ‘java.util’ package.

Syntax

Collections.sort(nameOfcollection);

Algorithm

  • Step 1 − Create a class ‘Cart’ that implements Comparable Interface. Inside it, declare two variables and define a constructor of this class along with two parameters ‘item’ and ‘price’ of type string and double respectively.

  • Step 2 − Moving further we will convert the data of object into string using ‘toString()’ method. Then, define ‘compareTo’ method along with an object of class ‘Cart’ as a parameter to compare ‘this’ object with newly created object.

  • Step 3 − Now, in the main() method, declare an object named ‘obj’ of class ‘Cart’ of LinkedHashMap and using inbuilt method named ‘put()’ store the details of object to it. The ‘item’ is key and its corresponding value is ‘price’.

  • Step 4 − At the end, define an ArrayList collection named ‘SrtList’ to store the sorted elements of LinkedHashMap. Now, pass ‘obj’ as an argument to the method ‘Collections.sort()’ to perform sorting operation by values.

Example

import java.util.*;
import java.lang.*;
public class Cart implements Comparable<Cart> {
   String item;
   double price;
   Cart(String item, double price) {
      // this keyword shows these variables belongs to constructor
      this.item = item; 
      this.price = price;
   }
   // method for converting object into string
   public String toString() {
      return "Item: " + item + ", " + "Price: " + price;
   }
   public String getName() { 
      // to retrieve item name
      return this.item;
   }
   // overriding method
   public int compareTo(Cart comp) {
      if(this.price > comp.price) {
         return 1;
      } else {
         return -1;
      }
   }
   public static void main(String[] args) {
      // Declaring collection LinkedHashMap
      LinkedHashMap<String, Cart> obj = new LinkedHashMap<>();
      // Adding object to the obj map
      Cart obj1 = new Cart("Rice", 59);
      obj.put(obj1.getName(), obj1);
      Cart obj2 = new Cart("Milk", 60);
      obj.put(obj2.getName(), obj2);
      Cart obj3 = new Cart("Bread", 45);
      obj.put(obj3.getName(), obj3);
       // printing details obj map in unsorted order
      System.out.println("Elements of the map: ");
      for (String unKey : obj.keySet()) {
         System.out.println(obj.get(unKey));
      }
      List<Cart> SrtList = new ArrayList<>(obj.values());
      Collections.sort(SrtList); 
      // Sorting the object
      // printing details of obj map in sorted order
      System.out.println("Elements of the newly sorted map: ");
      System.out.println(SrtList);
   }
}

Output

Elements of the map: 
Item: Rice, Price: 59.0
Item: Milk, Price: 60.0
Item: Bread, Price: 45.0
Elements of the newly sorted map: 
[Item: Bread, Price: 45.0, Item: Rice, Price: 59.0, Item: Milk, Price: 60.0]

Conclusion

In Java version 1.0, the comparable interface was first introduced and made available in ‘java.lang’ package. In this article, we have explored LinkedHashMap and the use of Comparable Interface in sorting operation.

Updated on: 15-May-2023

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements