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 sot 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]
- 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.
Pseude Code: TreeSet<Integer> ts = new TreeSet<>(Collections.reverseOrder()); ts.addAll(lh);
Element in desending order : [26, 25, 24, 23, 22, 21]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.