Apologies for the newbie question, but what's the proper way to get a Set
(say LinkedHashSet
) in reverse order? For Collection
s there's Collections.reverse(Collection c)
, but how does one do it for a Set
with ordered elements (like a LinkedHashSet
)?
To sort TreeSet in descending order, use the descendingSet() method in Java. The descendingSet() method is used to return a reverse order view of the elements contained in this set.
To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.
: from the end to the beginning : so that what is first becomes last and what is last becomes first The movie tells the story of her life in reverse order. Let's have our meal in reverse order—dessert first!
To get the list in the reverse order, we need to use Collections. reverseOrder() and Collections. sort() methods together.
Sets are not ordered in general, so to preserve the sorting, after sorting the set as a list, you would need to use a known iteration order implementation of Set, such as LinkedHashSet
List list = new ArrayList(set);
Collections.sort(list, Collections.reverseOrder());
Set resultSet = new LinkedHashSet(list);
You could also use TreeSet with a comparator, but that is not as fast as the ArrayList method above.
public class LargestArray {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
Set<Integer> set = new TreeSet<>();
set.add(10);
set.add(20);
set.add(7);
set.add(4);
set.add(1);
set.add(2);
set.add(3);
set.add(4);
System.out.println("after Sorting");
for(int i : set) {
System.out.print(" " + i);
}
al.addAll(set);
set.clear();
Collections.reverse(al);
System.out.println();
System.out.println("After Reverse");
for (int i : al) {
System.out.print(" " + i);
}
}
}
output = after Sorting 1 2 3 4 7 10 20 After Reverse 20 10 7 4 3 2 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With