Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 201 ยท Generics and Functional Programming

Functional Programming in Java

Learn functional programming in Java - pure functions, immutability, higher-order functions, currying and partial application, composition, laziness, and recursion vs streams.

Java started as a strictly object-oriented language, but since Java 8 it has borrowed the most useful ideas from functional programming (FP): functions as values, pipelines that transform data instead of mutating it, and code built by combining small functions. You've already used the tools: lambdas, functional interfaces, method references, streams and Optional. This lesson is about the thinking that ties them together.

Functional style isn't an all-or-nothing choice. Modern Java code is usually a mix: objects to model the domain, and functional techniques where they make code easier to test, reason about and run in parallel. You'll learn what makes a function pure, why immutability matters, how to write functions that take and return other functions, how currying and composition work with Function, how to delay work with Supplier, and when recursion or a stream is the better tool, along with the honest limits of FP in Java.

Pure functions

A function is pure when it follows two rules:

  1. Same input, same output. Its result depends only on its arguments, not on fields, global state, the clock or random numbers.
  2. No side effects. It doesn't change anything outside itself: no modifying arguments or fields, no printing, no writing files.

Math.max(a, b) and String::toUpperCase are pure. A method that adds to a list field, reads LocalDate.now() or prints a log line is not.

Pure functions are easy to test (no setup, no mocks), safe to call from many threads, safe to cache, and easy to reason about: you can replace a call with its result without changing the program. That property is called referential transparency.

Java Impure vs pure versions of the same logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Real programs need side effects; a program that prints nothing and saves nothing is useless. The functional approach is to push side effects to the edges: a pure core that computes, and a thin outer layer that reads input, calls the core and writes results. That's the "functional core, imperative shell" design.

Immutability

Pure functions work best with immutable data: if values can't change, nothing can change them behind your back. Java gives you several tools:

Instead of cart.add(item), a functional style returns a new cart: Cart withItem(Item item). The old cart still exists unchanged, which makes undo, history and concurrent reads trivial. Creating new objects sounds expensive, but small, short-lived objects are cheap for the JVM's garbage collector.

Java Immutable updates with records and copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Higher-order functions

A higher-order function takes a function as a parameter, returns a function, or both. You've used plenty: stream.map(f), list.removeIf(predicate) and Comparator.comparing(keyExtractor) all take functions. Writing your own is how you remove duplication that differs only in behavior:

Java Writing higher-order functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

lengthBetween(3, 12) is a function factory: the returned lambda closes over min and max, remembering them after lengthBetween has returned. That's a closure. In Java, captured local variables must be effectively final, which fits FP perfectly: closures capture values, not changing variables.

Composition

Composition builds a new function by chaining existing ones: the output of one becomes the input of the next. Function provides two methods for it:

  • f.andThen(g): first f, then g. Reads in execution order.
  • f.compose(g): first g, then f. Reads like math notation, f(g(x)).

Predicate composes with and, or and negate; Comparator with thenComparing and reversed. Function.identity() returns its input unchanged and is the neutral element of composition, just as 0 is for addition. That makes it the identity for reducing a whole list of functions into one pipeline:

Java Composing functions into a pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last example is the essence of FP: behavior is data (a list of functions) that you can store, filter and combine like any other value.

Currying and partial application

Currying turns a function of several arguments into a chain of one-argument functions. In Java that's a Function that returns a Function:

Java
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;     // add.apply(2, 3)
Function<Integer, Function<Integer, Integer>> curried = a -> b -> a + b;
curried.apply(2).apply(3);   // 5

Why bother? Because supplying only the first argument gives you a specialized function, which is partial application. curried.apply(10) is "add 10," ready to pass to map. In practice, Java developers rarely curry everything; they use factory methods like lengthBetween above, which is the same idea with clearer names.

Java Currying and partial application

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The types get long fast: Function<String, Function<String, Function<String, String>>> is honest but hard to read. Java has no built-in curry helper or function-type shorthand, so keep currying to two levels, or define a small functional interface with a descriptive name.

Laziness with Supplier

FP languages often evaluate values only when needed. In Java, a Supplier<T> is a delayed computation: nothing happens until someone calls get(). You saw this with Optional.orElseGet; the same trick works for logging messages, expensive defaults and configuration. Combining a supplier with a cache gives memoization: compute once, reuse the result. Memoizing is only safe for pure functions, because a cached result skips any side effects.

Java
static <T> Supplier<T> memoize(Supplier<T> source) {
    return new Supplier<>() {
        private T value;
        private boolean done;

        public synchronized T get() {
            if (!done) {
                value = source.get();
                done = true;
            }
            return value;
        }
    };
}

For functions with arguments, map.computeIfAbsent(n, this::compute) is a common memo table, as shown in Recursion.

Recursion vs streams

Purely functional languages replace loops with recursion. Java can do that too, but with an important limit: the JVM doesn't optimize tail calls. Every recursive call adds a stack frame, so deep recursion (often from around ten thousand levels, depending on stack size) ends in a StackOverflowError.

Java Recursion depth vs streams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

So in Java:

  • Use streams (or loops) for processing sequences of any length; they're iterative under the hood.
  • Use recursion where the data is naturally recursive and shallow: trees, nested structures, divide-and-conquer algorithms with logarithmic depth.
  • Combine both freely: a recursive method that walks a tree can use streams for each node's children.

Limits of FP in Java

Java's functional features are powerful, but they're layered onto an object-oriented language, and a few rough edges are worth knowing:

  • Checked exceptions don't fit the standard functional interfaces; a lambda in map can't throw IOException. Wrap it or handle it inside a helper method.
  • No function types, only interfaces, so currying and generic signatures become verbose.
  • Boxing: Function<Integer, Integer> boxes every number; use IntUnaryOperator and friends in hot code.
  • Mutable defaults: ArrayList, arrays and most JDK classes are mutable, so immutability is a discipline, not a guarantee.
  • Debugging: long chains of lambdas produce long stack traces. Name your functions and keep pipelines short.

Use the functional style where it makes code clearer: data transformations, validation rules, configurable behavior and concurrency. Use plain objects and loops where they're simpler. Good Java code mixes both without dogma.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which method is pure?

    area depends only on its arguments and changes nothing. The others mutate state, print, or depend on the current date.
  2. 2. With f = x -> x + 1 and g = x -> x * 10, what is f.andThen(g).apply(2)?

    andThen runs f first (2 + 1 = 3), then g (3 * 10 = 30). f.compose(g) would give 2 * 10 + 1 = 21.
  3. 3. Given Function<Integer, Function<Integer, Integer>> mul = a -> b -> a * b;, what is mul.apply(4)?

    This is currying. Applying the first argument returns a new function waiting for b, which is partial application.
  4. 4. Why can a deeply recursive Java method fail where a stream over the same data works?

    Without tail-call optimization, recursion depth is limited by the thread's stack. Streams process elements iteratively, so their length is limited only by the data.
  5. 5. Which is a good reason to memoize a function?

    Caching results is only correct when the same input always gives the same output and skipping the call loses no side effects, which is exactly what purity guarantees.

Summary

  • Pure functions depend only on their inputs and have no side effects; they're easy to test, cache and run in parallel. Keep side effects at the edges of your program.
  • Immutable data (records, List.of, copies, "with" methods) makes pure code safe and gives you history and thread safety for free.
  • Higher-order functions take or return functions; returned lambdas are closures over effectively final values.
  • Compose with andThen/compose (plus and/or/negate, thenComparing); reduce a list of functions with Function.identity() and Function::andThen.
  • Currying (a -> b -> ...) and partial application create specialized functions; named factory methods are often clearer.
  • Supplier delays work and enables memoization of pure computations.
  • The JVM has no tail-call optimization: use streams or loops for long sequences, recursion for shallow recursive structures.

Next: Dates and Times, where the immutable, functional-friendly java.time API handles dates, times, time zones and durations.