Java Reference
In-Depth Information
Lambda Expressions
One of the most eagerly anticated features of Java 8 was the introduction of lambda
expressions. These allow small bits of code to be written inline as literals in a pro‐
gram and facilitate a more functional style of programming Java.
In truth, many of these techniques had always been possible using nested types, via
patterns like callbacks and handlers, but the syntax was always quite cumbersome,
especially given the need to explicitly define a completely new type even when only
needing to express a single line of code in the callback.
As we saw in Chapter 2 , the syntax for a lambda expression is to take a list of
parameters (the types of which are typically inferred), and to attach that to a
method body, like this:
( p , q ) -> { /* method body */ }
This can provide a very compact way to represent simple methods, and can largely
obviate the need to use anonymous classes.
m
e
A lambda expression has almost all of the component parts of
a method, with the obvious exception that a lambda doesn't
have a name. In fact, some developers like to think of lambdas
as “anonymous methods.”
For example, consider the list() method of the java.io.File class. This method
lists the files in a directory. Before it returns the list, though, it passes the name of
each file to a FilenameFilter object you must supply. This FilenameFilter object
accepts or rejects each file.
Here's how you can define a FilenameFilter class to list only those files whose
names end with .java , using an anonymous class:
File dir = new File ( "/src" ); // The directory to list
// Now call the list() method with a single anonymous implemenation of
// FilenameFilter as the argument
String [] filelist = dir . list ( new FilenameFilter () {
public boolean accept ( File f , String s ) {
return s . endsWith ( ".java" );
}
});
With lambda expressions, this can be simplified:
File dir = new File ( "/src" ); // The directory to list
String [] filelist = dir . list (( f , s ) -> { return s . endsWith ( ".java" ); });
Search WWH ::




Custom Search