I am having some confusion of how method references work in Java 8. I wrote the following code segment for filtering hidden files in a folder. They are producing correct result. I am not understanding -> how method signature of listFiles method is working for option 2 of this code segment.
This is what I found in Java 8 documentation
File[] listFiles()File[] listFiles(FileFilter filter)File[] listFiles(FilenameFilter filter)File[] hidden = f.listFiles((p)-> p.isHidden()); //Option 1 - function signature matching (based on my understanding)
for (int i = 0; i < hidden.length; i++) {
System.out.println(hidden[i]);
}
System.out.println("================================");
File[] hidden1 = f.listFiles(File::isHidden); //Option 2 - how this method call is working
for (int i = 0; i < hidden1.length; i++) {
System.out.println(hidden1[i]);
}
What is a method refernce
You can see a method reference as a lambda expression, that call an existing method.
Kinds of method references
There are four kinds of method references:
ContainingClass::staticMethodNamecontainingObject::instanceMethodNameContainingType::methodNameClassName::newHow to understand it?
The following expression that lists all hidden files:
f.listFiles(p -> p.isHidden());
This expression is composed by the instance method listFiles(FileFilter) and your lambda expression p -> p.isHidden() that is not a anonymous method but an existing instance method of the class File.
Note that FileFilter is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. Hence, you can write your expression f.listFiles(File::isHidden);
Side notes
p. For a better readibility, I would suggest to replace (p) with simply a p. Hence, your lambda expression will become p-> p.isHidden().for (File value : hidden) {
System.out.println(value);
}
Documentation:
Method reference
FileFilter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With