Java 8 Lambda Function

Posted on Posted in Java

Lambda functions – enables you to treat functionality as method arguments.

  • The forEach() method for handling a collection of data. In this case, we have a list of Person, instead of doing a for loop we are using lambda syntax:

For more complex methods you can wrap it in brackets, acting as anonymous classes.

Lambda expressions can also be used to easily overwrite SAM interfaces, or Single Abstract Method interface. These are interfaces that have one sole method that the developer needs to overwrite. Example are Runnable and Comparator interface.

Instead of creating classes to overwrite theses interface, these can be easily handle by lambda expressions, the below will sort person by name:

  • Similar to inner classes, lambda have access to it’s class variables

Static Method references using lambda

Note: in this case my class name is Program, and I have a static method called processPeople(), so looking at the below, for each person in my list, call the method processPeople(), which can be your method to do validation and then save to the database.

Instance Method References using lambda,

in this case, we have a separate PersonDAO class that has a method called saveToDB(), we needed to initialize the class and called it handler, from there now you can say forEach person in my list, use handler to saveToDBit is much simpler rather than using for loops or iterators to go through each value in your list.

 

Leave a Reply