Skip to lesson

Function and Predicate

A Function<T, R> turns a value of type T into a value of type R, and a Predicate<T> answers yes or no about a value of type T. Because both are objects, you can store a rule in a variable and hand it to a method.

Function<T, R>: turn one value into another

A Predicate<T> is a functional interface whose test method takes a T and returns true or false, used to decide whether a value passes a check.

Apps convert values all the time, such as marks to a grade. A Function<T, R> holds the conversion as an object: T is the input type, R the result type, and you run it with apply.

Example 1 · Function: marks to grade, rupees to paise

FunctionDemo.javaJava
import java.util.function.Function;
public class FunctionDemo {    public static void main(String[] args) {        Function<Integer, Integer> toPaise = rupees -> rupees * 100;
        Function<Integer, String> grade = marks -> {            if (marks >= 75) {                return "Distinction";            } else if (marks >= 60) {                return "First class";            } else if (marks >= 35) {                return "Pass";            }            return "Fail";        };
        System.out.println("Rs. 249 = " + toPaise.apply(249) + " paise");        int[] allMarks = {82, 64, 35, 21};        for (int m : allMarks) {            System.out.println(m + " -> " + grade.apply(m));        }    }}
Output
Rs. 249 = 24900 paise
82 -> Distinction
64 -> First class
35 -> Pass
21 -> Fail

What this code does

  • Function<Integer, Integer> takes an Integer and returns an Integer; apply(249) runs the lambda with rupees = 249.
  • grade is a block lambda: braces, an if chain and a return on every path. Its result type, String, comes from the second type argument.
  • The int values in the array are boxed to Integer automatically when passed to apply.

A fixed method such as static String grade(int marks) works, but it cannot be stored in a variable or handed to another method. Function<Integer, String> grade reads as "a function from Integer to String".

When the body needs more than one expression, use a block lambda: braces, statements and a return. For example m -> { if (m >= 75) return "A"; return "B"; }. Every path through the block must return a value of type R.

Generic types must be class types. Write Function<Integer, Integer>, never Function<int, int>; Java boxes the int for you.

Predicate<T>: a yes/no rule

A Function<T, R> is a functional interface whose apply method takes a T and returns an R, used to turn one value into another.

A predicate is a rule that is either true or false for a value. "Is the phone number 10 digits?", "Did the student pass?" and "Is the order above Rs. 499 for free delivery?" are all predicates.

Example 2 · Predicate: is the phone number valid, did the student pass

PredicateDemo.javaJava
import java.util.function.Predicate;
public class PredicateDemo {    public static void main(String[] args) {        Predicate<Integer> passed = marks -> marks >= 35;
        Predicate<String> validPhone = phone -> {            if (phone.length() != 10) {                return false;            }            for (char c : phone.toCharArray()) {                if (!Character.isDigit(c)) {                    return false;                }            }            return true;        };
        System.out.println("42 passed? " + passed.test(42));        String[] phones = {"9845012345", "98450", "98450A2345"};        for (String p : phones) {            if (validPhone.test(p)) {                System.out.println(p + " is valid");            } else {                System.out.println(p + " is not valid");            }        }    }}
Output
42 passed? true
9845012345 is valid
98450 is not valid
98450A2345 is not valid

What this code does

  • test returns a plain boolean, so validPhone.test(p) goes straight into an if.
  • The block lambda returns false as soon as one check fails: first the length, then any character that is not a digit. Only a number that survives both checks reaches return true.

Predicate<T> has one method, boolean test(T t). It is different from Function<T, Boolean> in one useful way: it returns a plain boolean, so it fits straight into an if or a while. A rule like "10 characters and all of them digits" is too long for one expression, so write it as a block lambda with a loop, and return false as soon as one character fails.

Passing behaviour into a method

Suppose a class report needs the students who passed, then those in section A, then the toppers. The brute force way is three methods, filterPassed, filterSectionA and filterToppers. Each copies the same loop and changes only one if condition.

  1. filterStudents(students, s -> s.marks() >= 35) is called.
  2. The method makes an empty result list and loops over the students.
  3. For each student it calls rule.test(s); the lambda runs with that student as s.
  4. If the answer is true, the student is added to the result, which is returned at the end.

Example 3 · One filter method, many rules

FilterStudentsDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.Predicate;
record Student(String name, int marks, char section) {    @Override    public String toString() {        return name + "(" + marks + ")";    }}
public class FilterStudentsDemo {    static List<Student> filterStudents(List<Student> list, Predicate<Student> rule) {        List<Student> result = new ArrayList<>();        for (Student s : list) {            if (rule.test(s)) {                result.add(s);            }        }        return result;    }
    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Rohan", 82, 'A'),                new Student("Aarav", 31, 'B'),                new Student("Kavya", 91, 'B'),                new Student("Divya", 58, 'A'));
        System.out.println("Passed:    " + filterStudents(students, s -> s.marks() >= 35));        System.out.println("Section A: " + filterStudents(students, s -> s.section() == 'A'));        System.out.println("Toppers:   " + filterStudents(students, s -> s.marks() >= 80));    }}
Output
Passed:    [Rohan(82), Kavya(91), Divya(58)]
Section A: [Rohan(82), Divya(58)]
Toppers:   [Rohan(82), Kavya(91)]

What this code does

  • The loop is written once, inside filterStudents. Each call passes a different rule, so three reports need one method instead of three copies of the same loop.
  • Predicate<Student> tells Java that s is a Student, so s.marks() and s.section() compile. The record overrides toString so each student prints as name(marks).

Example 4 · Passing a Function: one report, many formats

ReportFormatDemo.javaJava
import java.util.List;import java.util.function.Function;
record Student(String name, int marks, char section) {}
public class ReportFormatDemo {    static void printReport(List<Student> list, Function<Student, String> format) {        for (Student s : list) {            System.out.println("  " + format.apply(s));        }    }
    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Rohan", 82, 'A'),                new Student("Kavya", 91, 'B'));
        System.out.println("Marks sheet:");        printReport(students, s -> s.name() + ": " + s.marks());
        System.out.println("Notice board:");        printReport(students, s -> s.name().toUpperCase() + " (" + s.section() + ")");    }}
Output
Marks sheet:
  Rohan: 82
  Kavya: 91
Notice board:
  ROHAN (A)
  KAVYA (B)

What this code does

  • printReport decides when to print and in what order; the Function<Student, String> decides what each line looks like.
  • A new format needs only a new lambda at the call site. The method itself never changes.

The better way is one method with the condition as a parameter: filterStudents(List<Student> list, Predicate<Student> rule). The method owns the loop and calls rule.test(s) for each student. The caller owns the condition and passes it as a lambda. This is called passing behaviour: the method receives what to check, not only what data to use. A Function parameter works the same way. printReport(list, formatter) can print each student as "Rohan: 82" today and as "ROHAN (A)" tomorrow without changing the method.

Trap: forgetting the generic types

If you write Function f = m -> m * 2; without the angle brackets, you get a raw type. A raw type is a generic type used without its type arguments, so Java treats every input and result as Object.

Example 5 · Mistake: a raw Function gives you Object

RawTypeDemo.javaJava
import java.util.function.Function;
public class RawTypeDemo {    public static void main(String[] args) {        Function toPaise = rupees -> rupees * 100;        System.out.println(toPaise.apply(249));    }}
Sample compiler output
RawTypeDemo.java:5: error: bad operand types for binary operator '*'
        Function toPaise = rupees -> rupees * 100;
                                            ^
  first type:  Object
  second type: int
Note: RawTypeDemo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

What this code does

  • Without <Integer, Integer>, Function is a raw type, so the lambda parameter rupees is an Object. Object has no * operator, so the line does not compile.
  • The fix is to write the types: Function<Integer, Integer> toPaise = rupees -> rupees * 100;. With a raw type, even code that compiles returns Object and needs casts everywhere.

Then nothing works as expected. m * 2 fails because * is not defined for Object. A call like s.length() fails with "cannot find symbol" because Object has no length(). And String g = grade.apply(80); fails because apply now returns Object. The fix is always the same: write the types, Function<Integer, String> and Predicate<String>. The compiler then knows the lambda's parameter type and the result type.

Next step

Check your understanding

11 quick questions