167. Lambdas in a nutshell

Dissecting a lambda expression will reveal three main parts, as shown in the following diagram:

The following is a description of each part of a lambda expression:

  • On the left-hand side of the arrow, we have the parameters of this lambda that are used in the lambda body. These are the parameters of the FilenameFilter.accept​(File folder, String fileName) method.
  • On the right-hand of the arrow, we have the lambda body, which in this case checks if the folder in which the file was found can be read and if the file name ends with the .pdf suffix.
  • The arrow is just a separator of the lambda's parameters and body.

The anonymous class version of this lambda is as follows:

FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File folder, String fileName) {
return folder.canRead() && fileName.endsWith(".pdf");
}
};

Now, if we look at the lambda and the anonymous version of it, then we can conclude that a lambda expression is a concise anonymous function that can be passed as an argument to a method or kept in a variable. We can conclude that a lambda expression can be described according to the four words shown in the following diagram:

Lambdas sustain Behavior Parameterization and that is a big plus (check the previous problem for a detailed explanation of this). Finally, keep in mind that lambdas can be used only in the context of a functional interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset