data-driven-docs

Selft training repo


Project maintained by ggranados Hosted on GitHub Pages — Theme by mattgraham

Built-in Functional Interfaces


Table of Contents

Overview

Functional interfaces, which are gathered in the java.util.function 1 package, satisfy most developers’ needs in providing target types for lambda expressions and method references. Each of these interfaces is general and abstract, making them easy to adapt to almost any lambda expression. Developers should explore this package before creating new functional interfaces.

Consumer

Consumer<T>

Represents an operation that takes in one argument of type T and returns no result.

The real outcome is the side-effects it produces. Since it’s a functional interface, you can pass a lambda expression wherever a Consumer is expected.

Method: void accept(T t)

class Product {
  private double price = 0.0;

  public void setPrice(double price) {
    this.price = price;
  }

  public void printPrice() {
    System.out.println(price);
  }
}

public class Test {
  public static void main(String[] args) {
    Consumer<Product> updatePrice = p -> p.setPrice(5.9);
    Product p = new Product();
    updatePrice.accept(p);
    p.printPrice();
  }
}

Back to top

Supplier

Supplier<T>

Represents a supplier of results of type T.

This functional interface does the opposite of the Consumer, it takes no arguments but it returns some value. It may return different values when it is being called more than once. Since it’s a functional interface, you can pass a lambda expression wherever a Supplier is expected.

Method: T get()

public class Program {
    public static void main(String[] args) {
        int n = 3;
        display(() -> n + 10);
        display(() -> n + 100);
    }

    static void display(Supplier<Integer> arg) {
        System.out.println(arg.get());
    }
}

Back to top

Function

Function<T, R>

Represents a function that takes an argument of type T and returns a result of type R.

One use, for example, it’s to convert or transform from one object to another. Since it’s a functional interface, you can pass a lambda expression wherever a Function is expected.

Method: R apply(T t)

public class Test {
  public static void main(String[] args) {
    int n = 5;
    modifyTheValue(n, val-> val + 10);
    modifyTheValue(n, val-> val * 100);
  }

  static void modifyValue(int v, Function<Integer, Integer> function){
    int result = function.apply(v);
    System.out.println(newValue);
  }

}

Back to top

Predicate

Predicate<T>

Represents a predicate (boolean-valued function) that takes an argument of type T and returns a boolean result.

Method: boolean test(T t)

import java.util.function.Predicate;

public class PredicateExample {
  public static void main(String[] args) {
    Predicate<Integer> isEven = (num) -> num % 2 == 0;
    int number = 10;
    if (isEven.test(number)) {
      System.out.println(number + " is even.");
    } else {
      System.out.println(number + " is odd.");
    }
  }
}

Back to top

UnaryOperator

UnaryOperator<T>

Represents an operation on a single operand of type T, producing a result of the same type T.

Method: T apply(T t)

import java.util.function.UnaryOperator;

public class UnaryOperatorExample {
  public static void main(String[] args) {
    UnaryOperator<Integer> incrementByFive = (num) -> num + 5;
    int result = incrementByFive.apply(10);
    System.out.println("Result: " + result);
  }
}

Back to top

BinaryOperator

BinaryOperator<T>

Represents an operation upon two operands of type T, producing a result of type T.

Method: T apply(T t1, T t2)

import java.util.function.BinaryOperator;

public class BinaryOperatorExample {
    public static void main(String[] args) {
        BinaryOperator<Integer> sum = (a, b) -> a + b;
        int result = sum.apply(10, 20);
        System.out.println("Sum: " + result);
    }
}

Back to top

BiFunction

BiFunction<T, U, R>

Represents a function that takes two arguments of types T and U, and returns a result of type R.

Method: R apply(T t, U u)

import java.util.function.BiFunction;

public class BiFunctionExample {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
        int result = add.apply(10, 20);
        System.out.println("Result: " + result);
    }
}

Back to top

BiPredicate

BiPredicate<T, U>

Represents a predicate (boolean-valued function) that takes two arguments of types T and U, and returns a boolean result.

Method: boolean test(T t, U u)

import java.util.function.BiPredicate;

public class BiPredicateExample {
    public static void main(String[] args) {
        BiPredicate<Integer, Integer> areEqual = (a, b) -> a.equals(b);
        int num1 = 10;
        int num2 = 10;
        if (areEqual.test(num1, num2)) {
            System.out.println("The numbers are equal.");
        } else {
            System.out.println("The numbers are not equal.");
        }
    }
}

Back to top


Primitive Functional Interfaces

Java provides specialized versions of the functional interfaces to avoid autoboxing operations when the inputs or outputs are primitives.

For example, instead of using

Predicate<Integer> p = i -> i > 10;

You can use

IntPredicate p = i -> i > 10;

In general, the names of functional interfaces that have a primitive version for the input parameter are preceded by the primitive type, like IntPredicate. The Function interface also has variants for the output parameter like ToIntFunction<T>.

Summary of the primitive version of functional interfaces:

Back to top

Predicate

Back to top

Consumer

Back to top

Function

Back to top

Supplier

Back to top

UnaryOperator

Back to top



Ref.

https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html https://www.baeldung.com/java-8-functional-interfaces https://eherrera.net/ocpj8-notes/04-lambda-built-in-functional-interfaces#:~:text=In%20Java%208%2C%20a%20Predicate,the%20methods%20of%20this%20interface.


Get Started | Languages | Java Development | Java 8 | PF in Java


  1. https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/function/package-summary.html