$show=/label

Java 8 Functional Interfaces (FI)

SHARE:

Quick and practical guide to Functional Interfaces present in Java 8. If the interface has only one abstract method then as called Function Interface.

1. Overview

In this tutorial, We'll learn about Functional Interface added to Java 8. Functional Interface is abbreviated as FI.

These Functional Interfaces are used extensively in Lambda Expressions.

Please read article on "A Complete Guide to Lambda Expressions"

If you have a basic understanding of Lambda's that will help in using Functional Interface(FI) properly. But, We will discuss in short about Lambda's.

Java 8 Functional Interfaces (FI)


We will cover the following concepts in this article.


  • Intro to Lambda
  • Lambda Examples
  • Functional Interface Definition
  • @FunctionalInterface annotation
  • Built-in FI's
  • Types of Functional Interfaces with examples




2. Lambda Expression and Examples


Before Lambda's introduction, We were using anonymous inner classes widely in our applications. Lambda Expression denotes a function or method without any name to it. But it takes method arguments, body, and valid return type.

We will write a program to create a Thread using Runnable interface using an anonymous inner class.

2.1 Runnable with Anonymous Inner Class


We will be demonstrating anonymous inner class usage with the Runnable interface. The runnable interface has a method called run() which should have the thread implementation.

package com.java.w3schools.blog.java8.functional;

public class ThreadCreation {

 public static void main(String[] args) {

  Thread t = new Thread(new Runnable() {
   @Override
   public void run() {
    System.out.println("Thread execution started.");
   }
  });

 }
}

t.start();

Output:

A Runnable anonymous inner class object is created and passed to Thread class. Invoking t.start() will initiate the thread and starts execution. See the below output.

Thread execution started.

2.2 Runnable with Lambda's


In the above program, using an anonymous inner class for the Runnable interface is having many lines of code. But, the same code can be reduced to a few lines using new java 8 lambda expressions syntax.

Just see the below code.

Thread lambdaThread = new Thread(() -> System.out.println("Lambda Trhead exection started."));
lambdaThread.start();

Now, the new code written in lambda is in a single line. Removed all boilerplate code and converted it to more readable as well as easy to maintain.


3. Functional Interface Definition


In simple words, If the interface has only one abstract method then it is called Function Interface(FI).
All of FI's implementations can be used with Lambda.

You already know many Function Interface's that are available before Java 8 also. They are Comparable, Runnable, Callable, etc. But these are not declared as FunctionalInterface.

3.1 @FunctionalInterface Annotation


We can define any interface @FunctionalInterface annotation but it shows compile error if not having exactly one abstract method.

This annotation is very helpful to avoid accidentally adding additional abstract methods or removing the existing ones. Hence, stops breaking other code.

Note: This annotation is not mandatory and it is optional.

@FunctionalInterface
interface RunParellel {
boolean run();
}

We can explicitly identify a functional interface using the @FunctionalInterface annotation as above.

Compiler error : "The target type of this expression must be a functional interface"

Note: To create a custom Functional Interface, We must annotate the interface with @FunctionalInterface. That's all, From now this can be used with Lambda.

4. Built-in Functional Interfaces


Java 8 introduced a lot of Functional Interfaces as part of JDK 8. All are bundled into package java.util.function and total 43 functional interfaces.

All these are divided into 4 categories.

A) Suppliers
B) Consumers
C) Predicates
D) Functions

All these functional interfaces are having exactly only one abstract method (these may have static or default and private methods)

Private methods in interfaces are introduced in Java 9.

Note: The abstract method inside a Functional Interface is called as Functional Method.

We'll be using this "Functional Method" terminology in this tutorial from now onwards.

Built-in all FI's in java.util.function package

4.1 Suppliers


Suppliers always return some value and never takes an argument.

Supplier is a Functional Interface which has get() functional method. This is present in java.util.function package.

T get()

Example:

package com.java.w3schools.blog.java8.functional;

import java.util.function.Supplier;

/**
 * Supplier Interface in Java with Examples
 * 
 * @author Venkatesh
 *
 */
public class SupplierExample {

 public static void main(String[] args) {

// This Supper always return a random value
  Supplier randomValue = () -> Math.random();
  System.out.println(randomValue.get());
 }
}

Output:

0.8141135990476829

4.2 Consumers


Consumers consume values. java.util.function.Consumer’s has a functional method accept(). This FI always takes an argument and never returns anything.

This is just consuming the value or object passing to accept() functional method.

Consumer has two methods. One abstract method and one defalut method.

Functional Method: void accept(T t)
Default Method: default Consumer andThen(Consumer after)

Example:

package com.java.w3schools.blog.java8.functional;

import java.util.function.Consumer;

/**
 * Consumer Interface in Java with Examples
 * 
 * @author venkatesh
 *
 */
public class ConsumerExample {
 public static void main(String[] args) {
  Consumer consumer = (String value) -> {
   System.out.println(value.toUpperCase());
  };
  consumer.accept("Welcome to Java W3schools blog");
 }
}

Output:

WELCOME TO JAVA W3SCHOOLS BLOG

4.3 Predicates


Predicates test things and this is used to perform logical operations.

java.util.function.Predicate’s have a functional method test().

This FI has total of 5 methods.

1 Functional Method:

boolean test(T t)

3 default methods:

default Predicate and(Predicate other)
default Predicate negate()
default Predicate or(Predicate other)

1 static method:

static  Predicate isEqual(Object targetRef)

These 4 default methods are very helpfull to perform logical operations such as and, or, negate or equal operations.

Note: Predicate always take an input argument and returns a boolean value. Inside this method, We can perform the requried operations. Finally, It returns true or false.

Example:

package com.java.w3schools.blog.java8.functional;

import java.util.function.Predicate;

/**
 * Predicate Interface in Java with Examples
 * 
 * @author Venkatesh
 *
 */

public class PredicateExample {
 public static void main(String[] args) {

  Predicate predicate = (String str) -> str.contains("Java");

  boolean isJavaDeveloper = predicate.test("Jhon is a Java Developer");

  if (isJavaDeveloper) {
   System.out.println("Yes, Jhon is a Java Developer. He can develop Java based web applications");
  } else {
   System.out.println("Jhob is not a Java developer.");
  }
 }
}

Output:

Yes, Jhon is a Java Developer. He can develop Java based web applications

Here, test() method takes String as argument and checks that string has a word "Java". If the string has Java then it returns true. Otherwise returns false.
In our example, the input string has a Java word. This predicate returns true.

4.4 Functions


Represents a function that accepts one argument and produces a result.

You can think of functions as the most generic of the functional interfaces. java.util.function.Function’s functional method, apply().

Interface Function

Type Parameters:

T - the type of the input to the function
R - the type of the result of the function 

This has 1 functional method, 2 default methods and 1 static method.

R apply(T t)


2 default methods:

default  Function compose(Function before)
default  Function andThen(Function after)

1 static method:

static  Function identity()

Example:

package com.java.w3schools.blog.java8.functional;

import java.util.function.Function;

/**
 * Function Interface in Java with Examples
 * 
 * @author Venkatesh
 *
 */
class FunctionExample {
 public static void main(String[] args) {
  Function function = (String input) -> input.substring(5);
  String output = function.apply("This is a test Function interface in java 8");
  System.out.println(output);
 }
}

Output:

is a test Function interface in java 8

In this example, It taken input type and Output type as String. In other words, apply() method takes String as input and returns String value.

5. Conclusion


In this tutorial, We've seen What is Function Interface(FI) and how FI's are used with Lambda Expression.

How to define a custom functional interface.

What are the Built-in FI's are in Java 8? Discussed 4 types of FI's such as Supplier, Consumer, Predicate, and Function.

All examples shown in this article are over GitHub.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Functional Interfaces (FI)
Java 8 Functional Interfaces (FI)
Quick and practical guide to Functional Interfaces present in Java 8. If the interface has only one abstract method then as called Function Interface.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjhguALeW5DtlLbdzxWbqCosEbhO3MCZYcILSbOtRBuEffnZ7BRQkEenJAVa16mPhBFjYw_kxKT_4Wk-WNpdLu9FS2Lv-8kles7Zzl20hn8_byPkSV0mijlIC1zA8IUuyn4rvMLKy1Mi6c/s320/Java+8+Functional+Interfaces+%2528FI%2529.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjhguALeW5DtlLbdzxWbqCosEbhO3MCZYcILSbOtRBuEffnZ7BRQkEenJAVa16mPhBFjYw_kxKT_4Wk-WNpdLu9FS2Lv-8kles7Zzl20hn8_byPkSV0mijlIC1zA8IUuyn4rvMLKy1Mi6c/s72-c/Java+8+Functional+Interfaces+%2528FI%2529.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/07/java-8-functional-interfaces.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/07/java-8-functional-interfaces.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content