Java中Comparator接口的thenComparingLong(java.util.function.ToLongFunction)方法將返回字典順序比較器,該函數具有提取Long排序鍵的函數。
用法:
default Comparator <T> thenComparingLong( ToLongFunction <T> keyExtractor)
參數:此方法接受keyExtractor,該函數用於提取Long排序鍵。
返回值:此方法返回一個由該字典順序排序的比較器,然後返回Long排序鍵。
異常:如果參數為null,則此方法將引發NullPointerException。
下麵的程序演示了thenComparingLong(java.util.function.ToLongFunction)方法:
示例1:
// Java program to demonstrate Comparator
// thenComparingLong(ToLongFunction) 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<Users> list = createUsers();
System.out.printf("before sort: %s%n", list);
Collections.sort(list,
Comparator
.comparing(Users::getDepartment)
.thenComparingLong(Users::getId));
System.out.printf("after sort: %s%n", list);
}
private static List<Users> createUsers()
{
return Arrays.asList(
new Users(12311, "ME"),
new Users(10211, "CSE"),
new Users(33111, "CSE"),
new Users(21000, "IT"),
new Users(12133, "IT"),
new Users(21445, "CSE"));
}
private static class Users {
private long id;
private String department;
public Users(long id, String department)
{
this.id = id;
this.department = department;
}
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getDepartment()
{
return department;
}
public void setDepartment(String department)
{
this.department = department;
}
@Override
public String toString()
{
return department + " - " + id;
}
}
}
IDE的控製台上打印的輸出如下所示。
輸出:
您可以在示例中看到,首先按部門進行排序,如果部門相同,則按ID進行排序。
示例2:
// Java program to demonstrate Comparator
// thenComparingLong(ToLongFunction) method
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class GFG {
public static void main(String... args)
{
List<String> list
= Arrays.asList("KKR", "CSK",
"MI", "KXIP", "RCB",
"SRH", "DC", "RR");
try {
// apply thenComparingLong
Comparator.comparing(list::get)
.thenComparingLong(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 reversed()用法及代碼示例
- Java Comparator thenComparingInt()用法及代碼示例
- Java SortedMap comparator()用法及代碼示例
- Java Comparator reverseOrder()用法及代碼示例
- Java Comparator comparingLong()用法及代碼示例
- Java TreeMap comparator()用法及代碼示例
- Java Comparator comparingDouble()用法及代碼示例
- Java Comparator thenComparingDouble()用法及代碼示例
- Java Comparator naturalOrder()用法及代碼示例
- Java Comparator nullsLast()用法及代碼示例
- Java ConcurrentSkipListSet comparator()用法及代碼示例
- Java Comparator nullsFirst()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Comparator thenComparingLong() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。