Every lambda in Java has a type. That type is a functional interface: an interface with just one abstract method. Java has dozens of ready-made ones in java.util.function. Learn the main four, Predicate, Function, Consumer and Supplier, and stream code becomes much easier to read. This lesson also shows how to combine functions, and a short form called the method reference.
In this lesson you will learn
- What makes an interface “functional”
Predicate,Function,Consumer,Supplierand their relatives- Combining with
and,negateandandThen - Writing your own functional interface
- The four kinds of method reference
You should know lambda expressions and interfaces.
The Core Functional Interfaces
| Interface | Method | Takes → gives | Typical use |
|---|---|---|---|
Predicate<T> | test | T → boolean | Filtering |
Function<T,R> | apply | T → R | Transforming |
Consumer<T> | accept | T → nothing | Printing, saving |
Supplier<T> | get | nothing → T | Creating values lazily |
BiFunction<T,U,R> | apply | T, U → R | Two inputs |
UnaryOperator<T> | apply | T → T | Same type in and out |
import java.util.function.*;
public class Main {
public static void main(String[] args) {
// The four core functional interfaces
Predicate<Integer> isPass = marks -> marks >= 33;
Function<Integer, String> grade = m -> m >= 80 ? "A+" : m >= 70 ? "A" : m >= 33 ? "Pass" : "Fail";
Consumer<String> shout = s -> System.out.println(s.toUpperCase());
Supplier<String> greeting = () -> "Shubho sokal";
System.out.println(isPass.test(45) + " " + isPass.test(20));
System.out.println(grade.apply(85) + " " + grade.apply(72) + " " + grade.apply(10));
shout.accept("hello");
System.out.println(greeting.get());
// Combining functions
Predicate<Integer> isTop = m -> m >= 80;
Predicate<Integer> passNotTop = isPass.and(isTop.negate());
System.out.println("55 pass but not top? " + passNotTop.test(55));
Function<Integer, Integer> addGrace = m -> m + 5;
Function<Integer, String> graceThenGrade = addGrace.andThen(grade);
System.out.println("75 with grace marks -> " + graceThenGrade.apply(75));
// Two inputs, and primitive versions that avoid boxing
BiFunction<Integer, Integer, Integer> total = (a, b) -> a + b;
IntUnaryOperator square = x -> x * x;
UnaryOperator<String> trim = String::trim;
System.out.println(total.apply(40, 45) + " " + square.applyAsInt(9) + " [" + trim.apply(" Java ") + "]");
}
}
Output
true false
A+ A Fail
HELLO
Shubho sokal
55 pass but not top? true
75 with grace marks -> A+
85 81 [Java]
- Each lambda is stored in a variable of a functional interface type. To run it, call the interface’s one method.
isPass.and(isTop.negate())builds a new predicate: “passed and not top”. Predicates also haveor.addGrace.andThen(grade)runs one function, then feeds its result to the next: 75 + 5 = 80, graded A+.- Versions such as
IntUnaryOperatorwork on plainintvalues, so no boxing is needed.
Custom Interfaces and Method References
import java.util.*;
import java.util.function.*;
public class Main {
// Your own functional interface: exactly one abstract method
@FunctionalInterface
interface Discount {
double apply(double price);
}
static class Text {
static String shortName(String s) { return s.substring(0, 3); }
}
public static void main(String[] args) {
Discount eid = p -> p * 0.8;
Discount flat = p -> Math.max(0, p - 100);
System.out.println("Eid price: " + eid.apply(1500) + ", flat price: " + flat.apply(1500));
List<String> cities = new ArrayList<>(List.of("Sylhet", "dhaka", "Khulna", "barishal"));
// Four kinds of method reference
cities.replaceAll(String::toUpperCase); // instance method of any object
cities.forEach(System.out::println); // instance method of a particular object
Function<String, String> abbr = Text::shortName; // static method
Supplier<List<String>> maker = ArrayList::new; // constructor
List<String> codes = maker.get();
for (String c : cities) codes.add(abbr.apply(c));
System.out.println(codes);
// Comparator is a functional interface too
cities.sort(Comparator.comparing(String::length).thenComparing(Comparator.reverseOrder()));
System.out.println(cities);
}
}
Output
Eid price: 1200.0, flat price: 1400.0
SYLHET
DHAKA
KHULNA
BARISHAL
[SYL, DHA, KHU, BAR]
[DHAKA, SYLHET, KHULNA, BARISHAL]
@FunctionalInterface is optional. With it, the compiler checks that the interface has just one abstract method. A method reference is a short lambda that only calls a method that already exists:
| Kind | Example | Same as |
|---|---|---|
| Static method | Text::shortName | s -> Text.shortName(s) |
| Instance method of a particular object | System.out::println | x -> System.out.println(x) |
| Instance method of any object of a type | String::toUpperCase | s -> s.toUpperCase() |
| Constructor | ArrayList::new | () -> new ArrayList<>() |
The last line sorts by length. Names of the same length go in reverse order. Comparator is a functional interface too.
Common Mistakes
- Adding a second abstract method to an interface used with lambdas. It stops being functional, and every lambda breaks.
- Changing local variables inside a lambda. Captured variables must be effectively final.
- Using a method reference that does not fit. The method’s parameters and return type must match the interface method.
- Using
Function<Integer,Integer>in hot loops whenIntUnaryOperatorwould avoid boxing.
Practice Exercises
Exercise 1. Write a Predicate<String> that is true for strings that are not blank and shorter than 10 characters.
Show answer
Predicate<String> notBlank = s -> !s.isBlank();
Predicate<String> shortText = s -> s.length() < 10;
Predicate<String> ok = notBlank.and(shortText);
// ok.test("Dhaka") is true; ok.test(" ") is false; ok.test("Chattogram") is false
Exercise 2. Rewrite x -> Integer.parseInt(x) and () -> new HashMap<String, Integer>() as method references.
Show answer
Integer::parseInt and HashMap::new.
Frequently Asked Questions
Can a functional interface have default methods?
Yes. Only abstract methods count. Predicate has one abstract method, test, plus default methods such as and, or and negate.
Are lambdas objects?
Yes. At run time a lambda is an object that implements the functional interface, so you can store it in variables, put it in collections and pass it to methods.
Summary
- A functional interface has exactly one abstract method; lambdas implement it.
- Predicate tests, Function transforms, Consumer uses, Supplier provides.
- Combine with
and,or,negate,andThen. - Method references are shorthand for lambdas that only call a method.
