I am new about Lambda, here is what the textbook (java in nutshell) says:
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)
and the book gives me an example :
File dir =new File("/src");
String[] fileList =dir.list((d,fName)->fName.endWith(".java"))
I understand this lambda will convert into a FilenameFilter
interface which is an @FunctionalInterface
It does match the description in the book
However I can use lambda here to when the sort()
is expecting to receive a Comparator
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();});
I look over its source code to find Comparator
is a @FunctionInterface
but it have two nondefault methods compare
and equals
.It is different from what the book says.