Close

Java Collections - Collections.reverseOrder() Examples

Java Collections Java Java API 


Class:

java.util.Collections

java.lang.Objectjava.lang.Objectjava.util.Collectionsjava.util.CollectionsLogicBig

Methods:

public static <T> Comparator<T> reverseOrder()

Returns a comparator that imposes the reverse of the natural ordering.



public static <T> Comparator<T> reverseOrder(Comparator<T> cmp)

Returns a comparator that imposes the reverse ordering of the specified comparator.


Examples


package com.logicbig.example.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ReverseOrderExample {

public static void main(String... args) {
List<String> list = Arrays.asList("one", "two", "three", "four");
Collections.sort(list, Collections.reverseOrder());
System.out.println(list);
}
}

Output

[two, three, one, four]




package com.logicbig.example.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ReverseOrderExample2 {

public static void main(String... args) {
List<Integer> list = Arrays.asList(5, 6, 7, 4, 9);
Collections.sort(list, Collections.reverseOrder());
System.out.println(list);
}
}

Output

[9, 7, 6, 5, 4]




package com.logicbig.example.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ReverseOrderExample3 {

public static void main(String... args) {
List<String> list = Arrays.asList("one", "two", "three", "four");
Collections.sort(list,
Collections.reverseOrder(ReverseOrderExample3::lastCharComparator)
);
System.out.println(list);
}

private static int lastCharComparator(String s1, String s2) {
return Character.compare(s1.charAt(s1.length() - 1), s2.charAt(s2.length()-1));
}
}

Output

[four, two, one, three]




See Also