How to Sort LinkedHashSet Elements in Descending Order in Java?
Last Updated :
17 Nov, 2022
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:
- Create HashSet to take input and store all the elements from the user.
- 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
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] args)
{
Set<Integer> linkhasset
= new LinkedHashSet<Integer>();
linkhasset.add( 26 );
linkhasset.add( 23 );
linkhasset.add( 24 );
linkhasset.add( 21 );
linkhasset.add( 25 );
linkhasset.add( 22 );
TreeSet<Integer> ts
= new TreeSet<>(Collections.reverseOrder());
ts.addAll(linkhasset);
System.out.println( "Element in descending order : "
+ ts);
}
}
|
Output
Element in descending order : [26, 25, 24, 23, 22, 21]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...