Skip to content
Related Articles

Related Articles

How to Sort LinkedHashSet Elements in Descending Order in Java?

Improve Article
Save Article
  • Last Updated : 17 Nov, 2022
Improve Article
Save Article

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.


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]


  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());



// Java Program to sort LinkedHashSet elements
// in descending order
// Importing java generic libraries
import java.util.*;
// 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
        // 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
        // Print all elements of TreeSet
        System.out.println("Element in descending order : "
                           + ts);


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



My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!