Open In App

How to Sort LinkedHashSet Elements in Descending Order in Java?

Last Updated : 17 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet iteration is through the elements in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned to the order in which they were inserted.

Elements in HashSet does maintain order while TreeSet maintains objects in sorted order defined by either comparable or comparator method in Java. TreeSet elements are sorted in ascending order by default. So now the problem that occurs is to sort given HashSet in descending order. So here with the help of a TreeSet is necessary to store the element in descending order.

Illustration:

Input : LinkedHashSet = [4, 3, 6, 5, 8]
Output: LinkedHashSet = [8, 6, 5, 4, 3]

Input: LinkedHashSet = [22, 44, 33, 66, 55]
Output: LinkedHashSet = [66, 55, 44, 33, 22]

Algorithm

  1. Create HashSet to take input and store all the elements from the user.
  2. Now, create TreeSet which stores the elements in decreasing order by adding all the elements from above HashSet in reverse order.
Pseudo Code: TreeSet<Integer> ts = new TreeSet<>(Collections.reverseOrder());
             ts.addAll(lh);

Example:

Java




// Java Program to sort LinkedHashSet elements
// in descending order
 
// Importing java generic libraries
import java.util.*;
import java.io.*;
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating and Initializing LinkedHashSet
        Set<Integer> linkhasset
            = new LinkedHashSet<Integer>();
 
        // Adding elements to above LinkedHashSet
        // Custom inputs
        linkhasset.add(26);
        linkhasset.add(23);
        linkhasset.add(24);
        linkhasset.add(21);
        linkhasset.add(25);
        linkhasset.add(22);
 
        // TreeSet storing elements in descending order by
        // adding all elements of HashSet in reverse order
        TreeSet<Integer> ts
            = new TreeSet<>(Collections.reverseOrder());
 
        // Add all elements from LinkedHashSet to TreeSet
        ts.addAll(linkhasset);
 
        // Print all elements of TreeSet
        System.out.println("Element in descending order : "
                           + ts);
    }
}


Output

Element in descending order : [26, 25, 24, 23, 22, 21]

 
 

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads