- Introduction to Lambda Expressions
- Lambda Expression Scope
- Method References
- Functional Interfaces
- Default and Static Methods on Interfaces
Java 8 Lambda Expressions: Lambdas, Method References, Static and Default methods on Interfaces.
Method References
Since a lambda expression is like an object-less method, wouldn't be nice if we could refer to existing methods instead of using a lamda expression? This is exactly what we can do with method references.
For example, imagine you frequently need to filter a list of Files based on file types. Assume you have the following set of methods for determining a file's type:
public class FileFilters {
public static boolean fileIsPdf(File file) {/*code*/}
public static boolean fileIsTxt(File file) {/*code*/}
public static boolean fileIsRtf(File file) {/*code*/}
}
Whenever you want to filter a list of files, you can use a method reference as in the following example
(assuming you already defined a method getFiles() that returns a Stream):
Stream<File> pdfs = getFiles().filter(FileFilters::fileIsPdf);
Stream<File> txts = getFiles().filter(FileFilters::fileIsTxt);
Stream<File> rtfs = getFiles().filter(FileFilters::fileIsRtf);
Method references can point to:
- Static methods.
- Instance methods.
- Methods on particular instances.
- Constructors (ie.
TreeSet::new)
For example, using the new java.nio.file.Files.lines method:
Files.lines(Paths.get("Nio.java"))
.map(String::trim)
.forEach(System.out::println);
The above reads the file "Nio.java", calls trim() on every line, and then prints out the lines.
Notice that System.out::println refers to the println method on an instance of PrintStream.
Challenge
How would you use a method reference to the parseInt method on the Integer class?
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Challenge
Using a method reference, call Main.print on all of the given attributes.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.