Sort a Set in reverse order

set in descending order c++
iterate set in reverse order java
sort set in java
sort in reverse order java
reverse the order in java
treeset sort by value
reverse sort in java
order set in 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)?

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.

How to sort TreeSet in descending order in Java?, Given a TreeSet in Java, task is to sort elements of TreeSet in Descending Order (descreasing order). Examples: Input : Set: [2, 3, 5, 7, 10, 20] Output : Set: [20,  Obtain a stream consisting of all elements of the list. Sort the stream in reverse order using Stream.sorted () method by passing Comparator.reverseOrder () to it that imposes the reverse of the natural ordering. We can also pass a lambda expression (a, b) -> b.compareTo (a) to Stream.sorted () method that defines the reverse sorting order.

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

TreeSet descendingSet() method in Java with Examples , The descendingSet() method of java.util.TreeSet<E> class is used to return a reverse order view of the elements contained in this set. The descending set is  To make a TreeSet Element in decreasing order, simple use descendingSet() method which is used to change the order of TreeSet in reverse order. Below is the implementation of the above approach:

Check this out

http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html#descendingSet()

If you use a TreeSet you can get reverse order by calling descendingSet.

Collections.reverseOrder() in Java with Examples, Collections.sort(al, Collections.reverseOrder());. // Let us print the sorted list. System.out.println( "List after the use of Collection.reverseOrder()" +. #This will sort the list temporarily into reverse alphabetical order. print(sorted(a, reverse=True) #This will sort the list temporarily into reverse order. print(sorted(a, reverse=False)

I will explain you with an example. Comments are added in mid of the code for better understanding.

public class ReverseLinkedHashSet {

    public static void main(String[] args) {

        // creating a LinkedHashSet object which is
        // of type String or any. Will take a example of String.
        HashSet<String> cars = new LinkedHashSet<String>();

        // adding car elements to LinkedHashSet object as below
        cars.add("Toyato");
        cars.add("Hundai");
        cars.add("Porshe");
        cars.add("BMW");

        // Iterating using enhanced for-loop to see the order.
        System.out.println("Insertion Order: Iterating LinkedHashSet\n");
        for(String car : cars) {
            System.out.println(car);

        // Output will be as below  
        //Toyato
        //Hundai
        //Porshe
        //BMW
        }

        // Now convert to ArrayList to rearrange to reverse
        // the linkedHashset
        List<String> listOfCars = new ArrayList<String>(cars);

        // to reverse LinkedHashSet contents
        Collections.reverse(listOfCars);

        // reverse order of LinkedHashSet contents
        // can be done as below
        System.out.println("\n\n\nReverse Order of LinkedHashSet\n");
        for(String car : listOfCars) {
            System.out.println(car);

        // Output will be as below  
        //BMW
        //Porshe
        //Hundai
        //Toyato    
        }
    }
}

Also, I suggest not to use LinkedhashSet without a strong reason. For a complex application, it will reduce the performance. Use HashSet instead.

How to sort TreeSet in descending order in Java?, by the integer value, then you'll need to do as these others suggested and create a new object and override the compareTo method, or use your own comparator. If you want to sort the list in reverse natural order, guava's Ordering has a reverse method: List<String> list = Ordering.natural().reverse().sortedCopy(asu2);

Java 8, I using solution below,

Set<String> setTest = new HashSet<>();

setTest.add("1");
setTest.add("2");
setTest.add("3");

List<String> list = new ArrayList<>(setTest);
list.sort(Collections.reverseOrder());
Set<String> result = new LinkedHashSet<>(list);

for (String item: result) {
    System.out.println("---> " + item);
}

Result:

---> 3
---> 2
---> 1

Work for me.

java: TreeSet order, How do you sort a set in ascending order in Python? First things first. We can’t sort a Java Set collection by calling Collections.sort() method on a Set. That is because most implementations of Java Set doesn’t have a concept of order. A Set is something without an order by definition in Java. In order to sort a Java Set we need to convert it to a list first. Java 7 and earlier

Python set sorted method, Given a Set, the task is to traverse this Set in reverse order. Examples: Input: set = [10 20 30 70 80 90 100 40 50 60] Output: 100 90 80 70 60 50 40 30 20 10  iterable - A sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator. reverse (Optional) - If True, the sorted list is reversed (or sorted in descending order). Defaults to False if not provided. key (Optional) - A function that serves as a key for the sort

How to traverse a C++ set in reverse direction, The descendingSet() method is used to return a reverse order view of the elements contained in this set. The descending set is backed by this set, so changes to the set are also reflected in the descending set and reverse. The sort () method sorts the elements of a given list in a specific ascending or descending order. The syntax of the sort () method is: list.sort (key=, reverse=) Alternatively, you can also use Python's built-in sorted () function for the same purpose. sorted (list, key=, reverse=)

java.util.TreeSet.descendingSet() Method, reverseOrder(), which by default sort List of Integer in reverse numeric order and List of String in reverse alphabetic order. It actually reverse  How to sort in descending order? sort() takes a third parameter that is used to specify the order in which elements are to be sorted. We can pass “greater()” function to sort in descending order. This function does a comparison in a way that puts greater element before.

Comments
  • A Set doesn't have an order. Can you clarify? Also, reverse takes a List.
  • @SotiriosDelimanolis In Java, TreeSets keep their items in sorted order. To get at the elements in reverse order, you can use the descendingSet() method. For LinkedHashSet, see this answer: stackoverflow.com/questions/10741902/…
  • A LinkedHashSet is not ordered it is Linked. If you want to loop over the items in reverse order of insertion use an Iterator.
  • @BoristheSpider It's really dependent on what you mean by "ordered". TreeSet maintains a "sorted" order, whereas LinkedHashSet maintains the insertion order (and thus does have a predictable iteration order.)
  • +1, why the downvote?
  • Wouldn't this be inefficient (memory-wise) with larger sets of data (as you'll end up having the same data in memory twice)? My input is a Set, not a List.
  • The Java Collections API doesn't seem to allow for a constant space sorting or an arbitrary Set. You may need to limit yourself to the SortedSet API to expect that from what I can tell.
  • Wouldn't the TreeSet re-order them after I have added them (and mix up the order)...?
  • No that is why requires a comparator to maintain the order. If the comparator isn't correctly implemented then yes your order can be very strange.
  • The OP is using a LinkedHashSet - this maintains insertion order. Putting the items into a TreeSet would obviously break this. Unless you supplied an explicit ordering comparator - which defeats the object somewhat.
  • Ah that was added in an edit. I'm surprised LinkedHashSet doesn't have a reverse iterator since the docs say the implementation is backed by a doubly linked list.
  • That was indeed added a minute, or two after I added the post. Sorry about that.