Heyyou
Heyyou

Reputation: 311

What does the function Collections.reverseOrder() do?

int min=Collections.min(list, Collections.reverseOrder());

What will be the output after executing the reverseOrder function?

Upvotes: 2

Views: 2121

Answers (4)

Dezso Gabos
Dezso Gabos

Reputation: 2452

java.util.Collections.reverseOrder() method is a java.util.Collections class method.

According to the javadoc:

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface. The natural ordering is the ordering imposed by the objects' own compareTo method public static Comparator reverseOrder()

You can find some other good examples on the following site: https://www.geeksforgeeks.org/collections-reverseorder-java-examples/

In your case the following expressions are equivalent:

 Collections.min(list, Collections.reverseOrder()) 

 Collections.max(list)

Upvotes: 3

Joop Eggen
Joop Eggen

Reputation: 109597

This seems like an interview question about Collections:

Now, Collections.reverseOrder is a Comparator that inverts the normal order, > becomes < and vice versa.

Hence the following statements are the same:

int max = Collections.min(list, Collections.reverseOrder());
int max = Collections.max(list);

And the result is the maximum instead.

There are no real speed penalties, as the list itself is not modied, the list is not copied. The complexity for a List is O(N): all elements need to be traversed.

Using a SortedSet like TreeSet instead of a List would be better - when feasible.

Upvotes: 5

raviraja
raviraja

Reputation: 706

sometimes it's better to see for yourself with the source code.

public static <T> Comparator<T> reverseOrder() {
    return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
}

REVERSE_ORDER is simply an object of ReverseComparator inner class.

  static final ReverseComparator REVERSE_ORDER = new ReverseComparator();

Upvotes: 3

Reddi
Reddi

Reputation: 743

Here is an example, this function simply inverts your numbers and they are low. Check this example, I hope you will understand what it does.

import java.util.*;

public class HelloWorld{

     public static void main(String []args){
        List<Integer> nums = Arrays.asList(1, 10, 5, 23, 2, 3);
        nums.stream()
            .forEach(System.out::println);

        nums.stream()
            .sorted(Comparator.reverseOrder())
            .forEach(System.out::println);
     }
}

Upvotes: 3

Related Questions