Java中Comparator接口的thenComparingInt(java.util.function.ToIntFunction)方法將返回字典順序比較器,並帶有提取int排序鍵的函數。
用法:
default Comparator <T> thenComparingInt(ToIntFunction <T> keyExtractor)
參數:此方法接受keyExtractor,該函數是用於提取Int排序鍵的函數。
返回值:此方法返回一個由該字典順序排序的比較器,然後返回Int排序鍵。
異常:如果參數為null,則此方法將引發NullPointerException。
以下示例程序旨在說明thenComparingInt(java.util.function.ToIntFunction)方法:
示例1:
// Java program to demonstrate Comparator
// thenComparingInt(ToIntFunction) method
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class GFG {
public static void main(String... args)
{
List<HardwareItems> list = getItems();
System.out.println("before sort:");
list.forEach(System.out::println);
// Apply sorting and
// also apply thenComparingInt()
Collections
.sort(
list,
Comparator
.comparing(HardwareItems::getName)
.thenComparingInt(HardwareItems::getPrice));
System.out.println("after sort:");
list.forEach(System.out::println);
}
private static List<HardwareItems> getItems()
{
return Arrays.asList(
new HardwareItems("Laptop", 40000),
new HardwareItems("Desktop", 20000),
new HardwareItems("Laptop", 45500),
new HardwareItems("Monitor", 10000),
new HardwareItems("Desktop", 22000));
}
private static class HardwareItems {
private String name;
private int price;
public HardwareItems(String name, int price)
{
this.name = name;
this.price = price;
}
public String getName()
{
return name;
}
public int getPrice()
{
return price;
}
@Override
public String toString()
{
return "HardwareItems [name="
+ name
+ ", price="
+ price + "]";
}
}
}
IDE的控製台上打印的輸出如下所示。
輸出:
您可以在示例中看到,首先按名稱進行排序,如果名稱相同,則按int類型的價格進行排序。
示例2:
// Java program to demonstrate Comparator
// thenComparingInt(ToIntFunction) method
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class GFG {
public static void main(String... args)
{
List<Double> list
= Arrays.asList(1.12, 2.4, 3.43,
4.343, 5.434);
try {
// apply thenComparingInt
Comparator.comparing(list::get)
.thenComparingInt(null);
}
catch (Exception e) {
System.out.printf("Exception:" + e);
}
}
}
控製台上打印的輸出如下所示。
輸出:
相關用法
- Java Collectors minBy(Comparator comparator)用法及代碼示例
- Java Collectors maxBy(Comparator comparator)用法及代碼示例
- Java Stream sorted(Comparator comparator)用法及代碼示例
- Java Comparator reverseOrder()用法及代碼示例
- Java Comparator reversed()用法及代碼示例
- Java SortedMap comparator()用法及代碼示例
- Java Comparator comparingLong()用法及代碼示例
- Java TreeMap comparator()用法及代碼示例
- Java Comparator thenComparingLong()用法及代碼示例
- Java Comparator comparingDouble()用法及代碼示例
- Java Comparator thenComparingDouble()用法及代碼示例
- Java Comparator naturalOrder()用法及代碼示例
- Java Comparator nullsLast()用法及代碼示例
- Java ConcurrentSkipListSet comparator()用法及代碼示例
- Java Comparator nullsFirst()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Comparator thenComparingInt() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。