cs notebook2
  • Introduction
  • functional interface
  • Lambda expressions
  • Stream
  • Method and Constructor Reference
  • Collectors
  • exe
  • Interface Changes
Powered by GitBook
On this page
  • Java Functional Interfaces
  • 1. Functional Interfaces Can Be Implemented by a Lambda Expression
  • 2. Built-in Functional Interfaces in Java
  • 2.1 Function
  • 2.2 Predicate
  • 2.3 Supplier
  • 2.4 Consumer

Was this helpful?

functional interface

PreviousIntroductionNextLambda expressions

Last updated 5 years ago

Was this helpful?

Java Functional Interfaces

A functional interface in Java is an interface that contains only one single abstract(unimplemented) method. A functional interface can contain default and static methods which do have an implementation, in addition to the single unimplemented method.

1. Functional Interfaces Can Be Implemented by a Lambda Expression

2. Built-in Functional Interfaces in Java

Java contains a set of functional interfaces designed for commonly occuring use cases.

2.1 Function

2.2 Predicate

The Java Predicateinterface, java.util.function.Predicate, represents a simple function that takes a single value as parameter, and returns true or false.

eg:

public interface Predicate{
    boolean test(T t);
}

public class CheckForNull implements Predicate{
    @Override
    public boolean test(Object o){
        return o!=null;
    }
}
Predicate predicate = (value)->value!=null;

2.3 Supplier

that represents a function that supplies a value of some sorts. The Supplier interface can also be thought of as a factory interface.

It does not take any arguments.

eg:

Supplier<Integer> supplier = ()-> new Integer((int)(Math.random()*1000D));

2.4 Consumer

that consumes a value without returning any value. A Java Consumer implementation could be printing out a value, or writing it to a file, or over the network etc.

eg:

Consumer<Integer> consumer = (value)->System.out.println(value);
http://tutorials.jenkov.com/java-functional-programming/functional-interfaces.html
https://www.baeldung.com/java-8-functional-interfaces