java - 为什么这个 lambda 可以在这里使用,其中需要 Arrays.sort() 中的比较器

标签 java lambda functional-programming java-stream

<分区>

我对 Lambda 不熟悉,教科书(简述 java)是这样说的:

Only certain types are eligible to be the target of a lambda . Target types are also called functional interfaces and they must:

  • Be interfaces
  • Have only one nondefault method(but may have other methods that are default)

这本书给了我一个例子:

File dir =new File("/src");
String[] fileList =dir.list((d,fName)->fName.endWith(".java"))

我知道这个 lambda 会转换成一个 FilenameFilter 接口(interface),它是一个 @FunctionalInterface 它确实符合书中的描述

enter image description here

不过,当 sort() 期望收到一个 Comparator

时,我可以在这里使用 lambda
        int n =12;
        Function<String,String[]> f = (s) -> {
            String[] ans = new String[n];();
            for (int i = 0; i < n; i++) {
                ans[i] = s;
            }
            return ans;};
        Arrays.sort(f.apply("colin"),(String s1 ,String s2)->{
            return s1.length() - s2.length();});

我查看了它的源代码,发现 Comparator 是一个 @FunctionInterface enter image description here

但是它有两个非默认的方法compareequals。和书上说的不一样。

最佳答案

equalsjava.lang.Object 的公共(public)方法。在识别功能接口(interface)时,这些方法明确不计算在内。

关于什么是函数式接口(interface)(以及什么可以通过 lambda“实现”)的真正权威定义可以在 Java 语言规范中找到。

几乎必然地,指南中对函数式接口(interface)的定义将不如 Java 语言规范中的定义那么严格和精确(因为后者是用一种不太适合初始语言的语言编写的学习一个概念,并且更好地创建同一事物的多个兼容实现)。

参见 JLS §9.8 Functional Interfaces (强调我的):

For an interface I, let M be the set of abstract methods that are members of I that do not have the same signature as any public instance method of the class Object. [...]

关于java - 为什么这个 lambda 可以在这里使用,其中需要 Arrays.sort() 中的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67077803/

相关文章:

java - java中设置数组的方法

java - CompareTo 与队列和链表

functional-programming - 在 SML 中优雅地打印二维数组

javascript - 这个高阶函数是如何工作的?

java - Android onCreate() 方法中的代码无法正常工作

java - 不幸的是,(应用程序名称)已停止 - Android 开发错误

python - 有没有更好的方法从 python 3 中的字符串中提取数字

c# - 将 Lambda 选择器作为参数传递

c++ - 如何避免在 decltype 表达式中指定变量?

haskell - 我如何读取这个孔错误