Java Lambda Expression Examples

Lambda expression in Java 8, enables to pass a functionality as a method argument. Lambda expressions is one of the hot topics in Java 8, which is about to be released. Few months back, I wrote article for introduction to Lambda expressions. In this article I will be presenting few examples using which we can understand Lamda expressions better. Needless to say, we need JDK 8 to work with lambda expressions and I used JDK 1.8 b115 Early Access Release.

1. Lambda Expression Hello World

This is a basic usage of lambda expression. HelloWorld is in an interface and on the fly at main method, we are providing a in implementation for that interface. After implementation, we use that instance and invoke its single methods. There will be always only one method and so the lambda expression need not specify the method name.

3. Function Argument in Lambda Expression

Slightly getting advanced with this example. We have got couple of implementations for the circle interface and they two different operations with respect to context. Those anonymous class implementations itself are passed as argument to another generic method, thus achieving a level of generic function.

6. Predicates and Lambda Expressions

Predicates mixes well with the lambda expressions. We can have a generic implementation and pass predicate as argument in lambda expression. Based on the condition, operation is performed inside the lambda implementation.

I have tried last example mentioned under section 6.Predicates and Lambda Expressions but i had reversed the condition of statement System.out.println(“Add Less Than 25: “+add(numList, n -> n n > 25)); and it results 0 which is bit surprising.