📜  Java中的比较器 thenComparingLong() 方法及示例

📅  最后修改于: 2022-05-13 01:54:19.058000             🧑  作者: Mango

Java中的比较器 thenComparingLong() 方法及示例

Java 中 Comparator 接口的 thenComparingLong( Java Java 函数 )方法返回一个字典顺序比较器,该比较器带有一个提取 Long 排序键的函数。

句法:

default Comparator  thenComparingLong(
    ToLongFunction  keyExtractor)

参数:此方法接受keyExtractor ,这是用于提取 Long 排序键的函数。

返回值:此方法返回由 this 和 Long 排序键组成的字典顺序比较器。

异常:如果参数为空,此方法将抛出 NullPointerException。

下面的程序说明 thenComparingLong(Java 函数.ToLongFunction) 方法:
方案一:

// 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 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 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 进行排序。

方案二:

// 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 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);
        }
    }
}

控制台上打印的输出如下所示。
输出:

参考: https: Java Java 函数)()