Java Built-In Functional Interfaces Cheatsheet and Examples

In order to use lambda expressions in Java 8, you need a functional interface. For most of your needs, you can use the already built ones in Java which are as follows:

  • Supplier – generate output without taking any input. For example, get the current date:
Supplier<LocalDate> getDate = () ->;

Then use getDate to assign a LocalDate variable:

LocalDate today = getDate.get();
  • Consumer – do something with a parameter without returning anything. For example, print some input:
Consumer<String> print = x -> System.out.println(x);

Then use print to print to system out a string:

  • Predicate – check whether something is true or false. For example, check if a string is empty:
Predicate<String> isStringEmpty = x -> x.isEmpty();

Use it to assign a boolean variable:

boolean isEmpty = isStringEmpty.test(""); //true
  • Function – turn one parameter into a potentially different type value and return it. For example, count the characters in a string:
Function<String, Integer> countCharacters = x -> x.length();

Use it to assign an integer variable:

int count = countCharacters.apply("test")); //count equals 4
  • UnaryOperator – a type of function where all parameters are the same. For example, convert all characters to uppercase:
UnaryOperator<String> toUpperCase = x -> x.toUpperCase();

Use it to convert “asd” to uppercase “ASD” string:

String upperCase = toUpperCase.apply("asd");

Most of the above have also a Bi variation such as BiConsumer. The Bi variation is simply double to what the single is. For example, BiConsumer consumes two parameters and etc.


So empty here ... leave a comment!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.