Java8 Lambda Examples


 Overview

    Java8 introduces the new feature named "Lambda Expression". This is not the new term which we are hearing, this is basically related to the same Lambda calculus which we learn in Mathematics. Basically, java supports the lambda expressions through the @FunctionInterface annotation. This enables functional programming in Java.

Functional Interface and the corresponding Annotation

    Java8 introduces lots of Functional Interfaces under java.util.function package. The functional interface is the interface that has only one method called Singel Abstract Method (SAM) interfaces. Any interface which has a single abstract method can be called the functional interface. But if we really want to create the new functional interface you better annotate that class with @FunctionalInterface. Look at the below example.




This package has interfaces that can be used for basic now and then use cases. We rarely need to create the new functional interface but if we want to we should use the @FunctionalInterface annotation.

Lambda Examples

    We will see how we can use the existing functional interfaces to code lambdas.

Predicate<?> : boolean test(T t);
    The predicates represent the operation that tests the conditions. It evaluates the condition on the given object and returns the boolean result,

Function<?> : R apply(T t)
    Functions represent the operations that transform the object to some other type by applying some logic.

Consumer<?> : void accept(T t)
    Consumers represent the operation that takes the single input element and returns nothing.

Supplier<?> : T get()
    The Supplier represents the operation that supplies the objects.

Below is the example of the above.



In the above example, we saw the enhanced version of Consumer lambda that is Method reference (::). When we have a method call in the lambda that exactly has a similar method signature as the used functional interface then we can replace the lambda with method reference to write the concise code.