Java 8 code KATAs III – FunctionalInterface & Lambda Expressions Example

In this series of posts, I will be posting simple java 8 code katas.

Part I – Interface with default methods
Part II – Interface with static methods
Part III – Functional Interfaces & Lambda Expressions
Part IV – Method References
Part V – java.util.function package
Part VI – Streams

This post would be about FunctionalInterface and Lambda Expressions.

See the example below:

LambdaExpressionsFunctionalInterfacesMain.java


package com.idodevjobs;

public class LambdaExpressionsFunctionalInterfacesMain {
    public static void main (String [] args) {
        FunctionalInterfacesExample example = (String message) -> {return "hello " + message;};
        System.out.println(example.sayHello("test"));
    }
}

@FunctionalInterface
interface FunctionalInterfacesExample {
    String sayHello (String message);
}


Java 8 has introduced a new annotation – FunctionalInterface to mark interfaces as a functional interface. Any interface with or without the annotation that has only one abstract method is treated as a functional interface and it can be implemented using lambda expression, method reference or anonymous class. A functional interface should contain only one abstract method and can have any number of static and default methods.

In this example, though its not a requirement, FunctionalInterfacesExample interface is annotated with FunctionalInterface annotation and sayHello is the only abstract method in the interface. LambdaExpressionsFunctionalInterfacesMain uses the sayHello method by implementing it using lambda expressions.

(String message) -> {return "hello " + message;}

This lambda expression is defined to implement the only abstract method in the interface. (String message) is the argument; {return “hello ” + message;} is the implementation.

Advertisements
This entry was posted in java and tagged . Bookmark the permalink.

5 Responses to Java 8 code KATAs III – FunctionalInterface & Lambda Expressions Example

  1. Pingback: Java 8 code KATAs I – Interface with default methods Example | iDoDevJobs

  2. Pingback: Java 8 code KATAs IV – Method References Example | iDoDevJobs

  3. Pingback: Java 8 code KATAs II – Interface with static methods Example | iDoDevJobs

  4. Pingback: Java 8 code KATAs V – java.util.function Example | iDoDevJobs

  5. Pingback: Java 8 code KATAs VI – Streams | iDoDevJobs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s