Java中Comparator Interface的reversed()方法返回一個比較器,該比較器強加此比較器的相反順序。如果您使用array的sort方法,並在應用反向方法後傳遞此比較器,則它將以相反的順序對數組進行排序。
用法:
default Comparator<T> reversed()
參數:此方法不接受任何內容。
返回值:該方法返回一個比較器,該比較器強加了此比較器的相反順序。
以下示例程序旨在說明reversed()方法:
示例1:
// Java program to demonstrate
// Comparator.reversed() method
import java.util.Arrays;
import java.util.Comparator;
public class GFG {
public static void main(String... args)
{
String[] Arraystrings
= { "aman", "amar", "avik" };
System.out.println("before sort : "
+ Arrays.toString(Arraystrings));
Comparator<String> comp = (String::compareTo);
Arrays.sort(Arraystrings, comp.reversed());
System.out.println("after sort : "
+ Arrays.toString(Arraystrings));
}
}
IDE的控製台上打印的輸出如下所示。
輸出:
示例2:
// Java program to demonstrate
// Comparator.reversed() method
import java.util.Arrays;
import java.util.Comparator;
public class GFG {
public static void main(String... args)
{
String[] list = { "KKR", "CSK",
"MI", "KXIP", "RCB",
"SRH", "DC", "RR" };
System.out.println("Before sorting:");
System.out.println(Arrays.toString(list));
Comparator<String> comp = (String::compareTo);
Arrays.sort(list, comp.reversed());
System.out.println("After sorting:");
System.out.println(Arrays.toString(list));
}
}
控製台上打印的輸出如下所示。
輸出:
參考文獻: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#reversed()
相關用法
- Java Collectors maxBy(Comparator comparator)用法及代碼示例
- Java Collectors minBy(Comparator comparator)用法及代碼示例
- Java Stream sorted(Comparator comparator)用法及代碼示例
- Java Comparator reverseOrder()用法及代碼示例
- Java Comparator comparingDouble()用法及代碼示例
- Java TreeMap comparator()用法及代碼示例
- Java Comparator naturalOrder()用法及代碼示例
- Java Comparator comparingLong()用法及代碼示例
- Java Comparator thenComparingInt()用法及代碼示例
- Java Comparator thenComparingLong()用法及代碼示例
- Java ConcurrentSkipListSet comparator()用法及代碼示例
- Java Comparator nullsFirst()用法及代碼示例
- Java SortedMap comparator()用法及代碼示例
- Java Comparator nullsLast()用法及代碼示例
- Java Comparator thenComparingDouble()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Comparator reversed() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。