Skip to lesson

Combine functions and predicates

An order is valid when it is paid, not cancelled and above a minimum amount. Writing one long rule is hard to read, so can you build it from small ones?

Why build big rules from small pieces

Function composition means building a bigger rule by joining small functions or predicates with default methods such as andThen, compose, and, or and negate. Each call returns a new function and leaves the originals unchanged.

Composing means building a big rule by joining small, named pieces, each tested on its own: adult, earnsEnough and goodScore become adult.and(earnsEnough).and(goodScore).

Java
Predicate<Applicant> adult = a -> a.age() >= 21;Predicate<Applicant> earnsEnough = a -> a.monthlyIncome() >= 25000;Predicate<Applicant> goodScore = a -> a.creditScore() >= 700;Predicate<Applicant> eligible = adult.and(earnsEnough).and(goodScore);  // nothing runs yetApplicant rohan = new Applicant("Rohan", 29, 48000, 742, false);System.out.println(eligible.test(rohan));  // true: now each piece is tested

A loan check needs age, income, credit score and history. One long lambda with every condition and nested ifs is hard to read, hard to test and impossible to reuse: the scholarship check cannot borrow its "income below limit" part. The joined rule reads like the bank's policy, and each piece can be reused in other rules.

This works because Function, Predicate and Consumer have default methods, ordinary methods with a body inside the interface. Calling one does not run anything yet. It builds a new lambda that will call the pieces later, when you call apply, test or accept.

andThen versus compose: the order trap

Both chain two functions, but in opposite order. f.andThen(g) runs f first, then g on its result: g(f(x)). f.compose(g) runs g first, then f: f(g(x)). andThen reads in the order it runs; compose reads like maths, inside out.

  1. discount.andThen(gst).apply(1000) first runs discount.apply(1000), which gives 900.
  2. It then runs gst.apply(900), which gives 1062, and returns it.
  3. discount.compose(gst).apply(1000) first runs gst.apply(1000), which gives 1180.
  4. It then runs discount.apply(1180), which gives 1080.
The order changes the answer. discount.andThen(gst) on 1000: discount first gives 900, then GST gives 1062. discount.compose(gst) on 1000: GST first gives 1180, then the discount gives 1080. Same two steps, different order, Rs. 18 apart.

Example 1 · andThen versus compose: discount and GST

AndThenComposeDemo.javaJava
import java.util.function.Function;
public class AndThenComposeDemo {    public static void main(String[] args) {        Function<Integer, Integer> discount = bill -> bill - 100;        Function<Integer, Integer> gst = bill -> bill * 118 / 100;
        Function<Integer, Integer> discountThenGst = discount.andThen(gst);        Function<Integer, Integer> gstThenDiscount = discount.compose(gst);
        System.out.println("Discount, then GST: " + discountThenGst.apply(1000));        System.out.println("GST, then discount: " + gstThenDiscount.apply(1000));        System.out.println("Same as gst.andThen(discount): " + gst.andThen(discount).apply(1000));    }}
Output
Discount, then GST: 1062
GST, then discount: 1080
Same as gst.andThen(discount): 1080

What this code does

  • discount.andThen(gst) runs discount first: 1000 becomes 900, then 1062. discount.compose(gst) runs gst first: 1180, then 1080.
  • f.compose(g) is always the same as g.andThen(f). Many teams use only andThen, because it reads in the order things happen.

Example 2 · Mistake: andThen on operators returns a Function

OperatorChainDemo.javaJava
import java.util.function.UnaryOperator;
public class OperatorChainDemo {    public static void main(String[] args) {        UnaryOperator<String> trim = s -> s.trim();        UnaryOperator<String> upper = s -> s.toUpperCase();        UnaryOperator<String> clean = trim.andThen(upper);        System.out.println(clean.apply("  pune "));    }}
Sample compiler output
OperatorChainDemo.java:7: error: incompatible types: no instance(s) of type variable(s) V exist so that Function<String,V> conforms to UnaryOperator<String>
        UnaryOperator<String> clean = trim.andThen(upper);
                                                  ^
  where V,R,T are type-variables:
    V extends Object declared in method <V>andThen(Function<? super R,? extends V>)
    R extends Object declared in interface Function
    T extends Object declared in interface Function
1 error

What this code does

  • andThen is a method of Function, and its return type is Function<T, V>. A UnaryOperator variable cannot hold a plain Function, so the assignment fails with a long message that ends in "conforms to UnaryOperator<String>".
  • Fix: declare Function<String, String> clean = trim.andThen(upper);. It still takes a String and returns a String; only the declared type changes.

The order changes the answer whenever the steps do not commute. Take a Rs. 100 discount and 18% GST on a Rs. 1000 bill. Discount then GST: 900, then 1062. GST then discount: 1180, then 1080. Same two steps, Rs. 18 difference. One type trap: andThen and compose are defined on Function, and they return a Function. So trim.andThen(upper) on two UnaryOperator<String> values gives a Function<String, String>, not a UnaryOperator<String>. Store the result in a Function variable.

Predict the output

Which order runs?

Read each chain, then pick what it prints.

Round 1 of 3

Function<Integer, Integer> discount = p -> p - 100;
Function<Integer, Integer> gst = p -> p * 118 / 100;
System.out.println(discount.andThen(gst).apply(1000));

Function.identity: the step that does nothing

Function.identity() returns a function that gives back its input unchanged: x goes in, x comes out. UnaryOperator.identity() is the same, typed as an operator.

Example 3 · Function.identity as the start of a pipeline

IdentityPipelineDemo.javaJava
import java.util.List;import java.util.function.Function;
public class IdentityPipelineDemo {    static Function<String, String> build(List<Function<String, String>> steps) {        Function<String, String> pipeline = Function.identity();        for (Function<String, String> step : steps) {            pipeline = pipeline.andThen(step);        }        return pipeline;    }
    public static void main(String[] args) {        Function<String, String> trim = s -> s.trim();        Function<String, String> lower = s -> s.toLowerCase();        Function<String, String> dotsToUnderscore = s -> s.replace('.', '_');
        Function<String, String> userId = build(List.of(trim, lower, dotsToUnderscore));        System.out.println(userId.apply("  Kavya.Rao "));
        Function<String, String> asTyped = build(List.of());        System.out.println("[" + asTyped.apply("  Kavya.Rao ") + "]");    }}
Output
kavya_rao
[  Kavya.Rao ]

What this code does

  • identity() is the empty pipeline. Each andThen adds one step at the end, so the steps run in list order: trim, lower case, then dots to underscores.
  • With no steps, the pipeline is just identity(), so the text comes back unchanged, spaces included. No special case for an empty list is needed.

It sounds useless, but it is the natural starting point when you combine an unknown number of steps in a loop: start with identity(), then pipeline = pipeline.andThen(step) for each step. If the list of steps is empty, the pipeline still works and changes nothing. It is also a clean "no change" choice when a method needs a function and you have nothing to do, for example a formatting option set to "as typed". The Streams lessons use it again when building maps.

Order of execution

Order of a built pipeline

Tap the steps in the order apply runs them.

Function<String, String> pipeline = Function.identity();
pipeline = pipeline.andThen(String::trim);
pipeline = pipeline.andThen(String::toUpperCase);
System.out.println(pipeline.apply(" pune "));

Predicate and, or, negate and Predicate.not

p.and(q) is true when both are true, p.or(q) when at least one is, and p.negate() flips the answer. They short-circuit like && and ||: if p is false, p.and(q) does not call q at all.

Example 4 · Predicate and, or, negate and Predicate.not

PredicateComboDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.Predicate;
record Order(String id, int amount, boolean paid, String city) {}
public class PredicateComboDemo {    public static void main(String[] args) {        Predicate<Order> isPaid = o -> o.paid();        Predicate<Order> bigOrder = o -> o.amount() >= 1000;        Predicate<Order> metroCity = o -> o.city().equals("Mumbai") || o.city().equals("Delhi");
        List<Order> orders = new ArrayList<>(List.of(                new Order("A1", 1500, true, "Pune"),                new Order("A2", 400, false, "Delhi"),                new Order("A3", 2200, false, "Mumbai"),                new Order("A4", 800, true, "Pune")));
        for (Order o : orders) {            System.out.println(o.id()                    + " paidAndBig=" + isPaid.and(bigOrder).test(o)                    + " bigOrMetro=" + bigOrder.or(metroCity).test(o)                    + " unpaid=" + isPaid.negate().test(o));        }
        orders.removeIf(Predicate.not(isPaid));        System.out.println("Paid orders left: " + orders.size());    }}
Output
A1 paidAndBig=true bigOrMetro=true unpaid=false
A2 paidAndBig=false bigOrMetro=true unpaid=true
A3 paidAndBig=false bigOrMetro=true unpaid=true
A4 paidAndBig=false bigOrMetro=false unpaid=false
Paid orders left: 2

What this code does

  • Each combined rule is built from the same three small predicates. isPaid.and(bigOrder) needs both; bigOrder.or(metroCity) needs either; negate() flips isPaid.
  • Predicate.not(isPaid) is the static form of isPaid.negate(). Passed to removeIf, it removes the unpaid orders A2 and A3.

Predicate.not(p) (Java 11) is a static method that returns p.negate(). It reads better when the rule is written right in a call: list.removeIf(Predicate.not(isPaid)) removes every order that is not paid. Watch the grouping. Chained calls run left to right, so a.or(b).and(c) means (a or b) and c. That is different from a || b && c, where && binds first. When a rule mixes and and or, build the inner group as its own variable first.

isPaid.negate() and Predicate.not(isPaid) give the same rule. Use whichever reads more like the sentence you are writing.

Consumer.andThen: two actions in turn

first.andThen(second) returns a Consumer that gives the same value to first, then to second. Printing a receipt and then saving it to a log becomes one action you can pass to forEach.

Example 5 · Consumer.andThen: print, then log

ConsumerChainDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.Consumer;
public class ConsumerChainDemo {    public static void main(String[] args) {        List<String> log = new ArrayList<>();
        Consumer<String> printReceipt = id -> System.out.println("Receipt printed for " + id);        Consumer<String> saveToLog = id -> log.add(id);        Consumer<String> sendSms = id -> System.out.println("  SMS sent for " + id);
        Consumer<String> checkout = printReceipt.andThen(saveToLog).andThen(sendSms);        List.of("UPI-501", "UPI-502").forEach(checkout);
        System.out.println("Log: " + log);    }}
Output
Receipt printed for UPI-501
  SMS sent for UPI-501
Receipt printed for UPI-502
  SMS sent for UPI-502
Log: [UPI-501, UPI-502]

What this code does

  • checkout gives each id to printReceipt, then saveToLog, then sendSms, always in that order. The whole chain is one Consumer, so forEach can take it.
  • Every step receives the same input; nothing is passed from one consumer to the next, because consumers return nothing.

The order is fixed: first always runs before second. If first throws an exception, second does not run. There is no compose for consumers, since a consumer returns nothing that another step could use.

Example 6 · Real-world use: loan eligibility from small rules

LoanRulesDemo.javaJava
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.function.Predicate;
record Applicant(String name, int age, int monthlyIncome, int creditScore, boolean pastDefault) {}
public class LoanRulesDemo {    public static void main(String[] args) {        Predicate<Applicant> rightAge = a -> a.age() >= 21 && a.age() <= 60;        Predicate<Applicant> earnsEnough = a -> a.monthlyIncome() >= 25000;        Predicate<Applicant> goodScore = a -> a.creditScore() >= 700;        Predicate<Applicant> cleanHistory = Predicate.not(a -> a.pastDefault());
        Predicate<Applicant> eligible = rightAge.and(earnsEnough).and(goodScore).and(cleanHistory);
        Map<String, Predicate<Applicant>> rules = new LinkedHashMap<>();        rules.put("age 21-60", rightAge);        rules.put("income", earnsEnough);        rules.put("credit score", goodScore);        rules.put("no past default", cleanHistory);
        List<Applicant> people = List.of(                new Applicant("Rohan", 29, 48000, 742, false),                new Applicant("Sana", 19, 30000, 710, false),                new Applicant("Vikram", 45, 22000, 680, true));
        for (Applicant a : people) {            if (eligible.test(a)) {                System.out.println(a.name() + ": eligible");                continue;            }            List<String> failed = new ArrayList<>();            rules.forEach((label, rule) -> {                if (!rule.test(a)) {                    failed.add(label);                }            });            System.out.println(a.name() + ": not eligible, fails " + failed);        }    }}
Output
Rohan: eligible
Sana: not eligible, fails [age 21-60]
Vikram: not eligible, fails [income, credit score, no past default]

What this code does

  • Four small rules, each one line, are joined with and into the full policy. The joined rule reads like the bank's own wording.
  • Because the pieces are separate objects, the same rules also explain why someone failed: the program tests each one by name. A scholarship check could reuse earnsEnough with a different limit next to it.

Next step

Check your understanding

12 quick questions