Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a Set in reverse order

Tags:

java

Apologies for the newbie question, but what's the proper way to get a Set (say LinkedHashSet) in reverse order? For Collections there's Collections.reverse(Collection c), but how does one do it for a Set with ordered elements (like a LinkedHashSet)?

like image 377
carlspring Avatar asked Mar 06 '14 00:03

carlspring


People also ask

How do you sort a set in reverse order?

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.

How do you reverse sort in Java?

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.

What is reverse order example?

: 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!

How do you sort a list in reverse order in Java 8?

To get the list in the reverse order, we need to use Collections. reverseOrder() and Collections. sort() methods together.


2 Answers

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.

like image 192
Peter Avatar answered Sep 21 '22 01:09

Peter


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

like image 24
Ved Prakash Avatar answered Sep 17 '22 01:09

Ved Prakash