Thursday, April 27, 2023

How to declare a method which takes a lambda expression in Java 8? Example Tutorial

You may have seen lot of examples of how to use lambda expression in Java 8 e.g. to replace anonymous class, to implement Runnable or to implement Comparator but there are hardly any examples of teaching you to how to declare your own user defined method which can accept lambda expression. In this tutorial, I will try to bridge that gap. Actually, a method doesn't know whether you are passing an instance or a lambda expression to it, all you need to remember is that lambda expression is of SAM type in Java 8. Which means, you can pass lambda expression in place of an interface which has just one abstract method. 

You might have seen it already like passing lambdas in place of Comparable, Comparator, Runnable, Callable and ActionListener? What is common between them? They all are interfaces with single abstract method. 

There is one more thing called functional interfaces, which is annotated by @Functional in Java 8. They are also interface with single abstract method intended to represent common functional programming requirement. 

Equipped with this knowledge you can say there are two ways to declare a method in Java 8 which can accept a lambda expression :

1) Declare a method which accept an interface with just one abstract method e.g. Runnable, Callable, or you own interface

2) Declare a method using existing functional interfaces from java.util.functional package.

Let's see an example of both of these approaches to declare a method with lambda as parameter. 


Method using functional type

Here is a method which accept a functional type in Java:

private static void process(Runnable r) {
        new Thread(r).start();
 }

here is how you can pass this method a lambda expression:

process(() -> {
  System.out.println("accepted lambda from a method");
});


Method using own interface to accept lambdas

Using your own interface has the advantage that you can have names that more clearly indicate the intent.

private static void print(Version v) {
  System.out.println(v.getVersion());
}

and here is how you can call this method by passing lambdas:

print(() -> {
  return 2;
});

Also, here are popular functional interfaces from Java which I believe, every Java programmer should learn:

How to declare method which takes a lambda expression in Java 8?




Java Program to create method to pass lambda expression

Here is our complete Java program to demonstrate how you can create a method to pass a Lambda expression in Java 8

/**
 * Java Program to demonstrate how to access local variable inside Anonymous
 * class and lambda expression in Java.
 *
 * @author WINDOWS 10
 *
 */
public class Java8Demo {

    public static void main(String... args) {

        process(() -> {
            System.out.println("accepted lambda from a method");

        });

        print(() -> {
            return 2;
        });
    }

    /**
     * process the Runnable into separate thread. Since Runnable is a functional
     * interface, you can pass lambda expression to this method.
     *
     * @param r
     */
    private static void process(Runnable r) {
        new Thread(r).start();
    }

    /**
     * This method accept a Version interface instance, since Version is a SAM
     * interface i.e. just has one abstract method, you can also pass lambda
     * expression to this method.
     *
     * @param v
     */
    private static void print(Version v) {
        System.out.println(v.getVersion());
    }

}

interface Version {

    int getVersion();
}


That's all about how to define a method which can take lambda expression as parameter in Java 8. Remember, method doesn't know anything about whether you are passing a regular instance of a lambda expression. If its a SAM type you can pass lambdas.

Other Lambda expression and Stream Tutorial you may like
  • Top 5 Courses to Learn Java 8 Programming (courses)
  • 50 Java 8 Stream and Lambda Interview questions (java 8 questions)
  • How to join String in Java 8 (example)
  • 20 Examples to learn new Date and Time API in Java 8 (example)
  • How to use filter() method in Java 8 (tutorial)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to use Stream class in Java 8 (tutorial)
  • How to change the date format of String in Java 8? (tutorial)
  • 10 Java Date, Time, and Calendar based Questions from Interviews (questions)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • 10 Examples to format and parse Date in Java 8? (tutorial)
  • How to compare two Dates in Java 8? (example)
  • How to use forEach() method in Java 8 (example)
  • How to convert Timestamp to Date in Java? (example)
  • Java 8 map + filter + stream example (tutorial)
  • 5 Free Courses to learn Java 8 and 9 (courses)

Thanks for reading this article so far. If you like this Java 8 tutorial about Lambda expression and functional interface then please share with your friends and colleagues. 

No comments :

Post a Comment