CodeGym /Courses /JAVA 25 SELF /Passing Functions as Parameters: Examples

Passing Functions as Parameters: Examples

JAVA 25 SELF
Level 49, Lesson 2
Available

1. Passing Behavior Instead of Data

Why pass a function as a parameter at all?

Imagine you have a method that sorts a list. But how does it know exactly how to sort? Alphabetically? By length? By date of birth? You could write a separate method for each case, but that quickly turns into copy-and-paste hell.

Instead, Java lets you pass behavior (that is, a function or a lambda) that defines how to sort, filter, transform, and so on. This makes your code flexible and reusable.

Example: sorting with a comparator

List<String> names = List.of("Anna", "Boris", "Vika");

// Passing behavior: how to compare elements (by string length)
names.stream()
     .sorted((a, b) -> a.length() - b.length())
     .forEach(System.out::println);

Example: filtering with a predicate

List<String> names = List.of("Anna", "Boris", "Vika");

// Passing behavior: who to keep (name longer than 4 characters)
names.stream()
     .filter(name -> name.length() > 4)
     .forEach(System.out::println);

In both cases you didn’t hardcode the logic into the method; instead, you gave it a piece of behavior that it applies to each element.

Benefits: less duplication, more flexibility

Instead of dozens of methods with similar code but different logic, you write one generic method that takes “what to do” as a function. This saves time, reduces errors, and makes the code easier to test.

2. Syntax for Passing Functions

Lambda expressions as arguments

The most common way is to write a lambda with the arrow -> right at the call site:

list.forEach(item -> System.out.println(item));

Or even shorter, if a suitable method already exists — a method reference (::):

list.forEach(System.out::println);

Method references

If you already have a suitable method, you can pass it as a reference with :::

// A regular method
public static boolean isLongName(String name) {
    return name.length() > 4;
}

// Passing a method reference
names.stream()
     .filter(MyClass::isLongName)
     .forEach(System.out::println);

This works if the method signature matches what the functional interface expects (Predicate<T>, Function<T, R>, Comparator<T>, etc.).

3. Examples from the Standard Library

Collections.sort and Comparator

List<String> names = new ArrayList<>(List.of("Anna", "Boris", "Vika"));

// Sort by name length
names.sort((a, b) -> a.length() - b.length());
System.out.println(names); // [Vika, Anna, Boris]

Stream.filter and Predicate

List<String> names = List.of("Anna", "Boris", "Vika");

// Keep only names starting with 'V'
names.stream()
     .filter(name -> name.startsWith("V"))
     .forEach(System.out::println); // Vika

Stream.map and Function

List<String> names = List.of("Anna", "Boris", "Vika");

// Transform names to upper case
names.stream()
     .map(String::toUpperCase)
     .forEach(System.out::println);

Optional.ifPresent and Consumer

Optional<String> opt = Optional.of("Hello!");

// If a value is present, print it
opt.ifPresent(s -> System.out.println("In the string: " + s));

4. Practice: Writing Your Own Methods with Function Parameters

Time to put the knowledge into practice! Let’s write a few methods that take a function as a parameter and use it inside.

Example 1: A method to process list elements (forEach your way)

Suppose we have a list of users (User). We want to perform some action on each user — for example, print a name, send an email, credit bonuses, and so on. Instead of hardcoding the action, we’ll pass it as a parameter — a Consumer<User>!

import java.util.List;
import java.util.function.Consumer;

class User {
    String name;
    int age;
    User(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class UserProcessor {
    // Method that takes a Consumer<User>
    public static void processUsers(List<User> users, Consumer<User> action) {
        for (User user : users) {
            action.accept(user);
        }
    }

    public static void main(String[] args) {
        List<User> users = List.of(
            new User("Anna", 25),
            new User("Boris", 30),
            new User("Vika", 22)
        );

        // Print all user names
        processUsers(users, user -> System.out.println("Name: " + user.name));

        // Credit a bonus (for the example, just print)
        processUsers(users, user -> System.out.println(user.name + " received a bonus!"));
    }
}

Example 2: A filtering method (Predicate)

Let’s write a method that returns only those users who match a condition (for example, only adults):

import java.util.List;
import java.util.ArrayList;
import java.util.function.Predicate;

public class UserFilter {
    public static List<User> filterUsers(List<User> users, Predicate<User> condition) {
        List<User> result = new ArrayList<>();
        for (User user : users) {
            if (condition.test(user)) {
                result.add(user);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<User> users = List.of(
            new User("Anna", 25),
            new User("Boris", 17),
            new User("Vika", 22)
        );

        // Filter only adults
        List<User> adults = filterUsers(users, user -> user.age >= 18);
        adults.forEach(user -> System.out.println(user.name)); // Anna, Vika
    }
}

Example 3: A mapping method (Function)

Now a method that turns a list of users into a list of their names (or any other transformation):

import java.util.List;
import java.util.ArrayList;
import java.util.function.Function;

public class UserMapper {
    public static <R> List<R> mapUsers(List<User> users, Function<User, R> mapper) {
        List<R> result = new ArrayList<>();
        for (User user : users) {
            result.add(mapper.apply(user));
        }
        return result;
    }

    public static void main(String[] args) {
        List<User> users = List.of(
            new User("Anna", 25),
            new User("Boris", 17),
            new User("Vika", 22)
        );

        // Get the list of names
        List<String> names = mapUsers(users, user -> user.name);
        System.out.println(names); // [Anna, Boris, Vika]

        // Get the list of ages
        List<Integer> ages = mapUsers(users, user -> user.age);
        System.out.println(ages); // [25, 17, 22]
    }
}

Example 4: A generator method (Supplier)

Sometimes you need to obtain a value “on demand” — for example, generate a random number, create an object, get the current time. The Supplier<T> interface is a good fit for that.

import java.util.function.Supplier;

public class ValueGenerator {
    public static int getValue(Supplier<Integer> supplier) {
        return supplier.get();
    }

    public static void main(String[] args) {
        // Get a random number
        int random = getValue(() -> (int)(Math.random() * 100));
        System.out.println("Random number: " + random);

        // Get the current time in milliseconds
        long time = getValue(System::currentTimeMillis);
        System.out.println("Time: " + time);
    }
}

5. Putting It All Together: Connecting the Examples

Let’s imagine we’re building a simple “User List” application. We can already:

  • Filter users by a condition (for example, only adults);
  • Map users to something else (names, emails, ages);
  • Perform actions on each user (printing, crediting bonuses);
  • Generate values on demand (for example, create new users).

Now, using all these methods, we can build flexible data-processing scenarios without rewriting code every time for a new task.

import java.util.*;
import java.util.function.*;

public class UserApp {
    static class User {
        String name;
        int age;
        User(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String toString() {
            return name + " (" + age + ")";
        }
    }

    // Generic method to process users
    static void processUsers(List<User> users, Consumer<User> action) {
        for (User user : users) action.accept(user);
    }

    // Generic filter
    static List<User> filterUsers(List<User> users, Predicate<User> condition) {
        List<User> result = new ArrayList<>();
        for (User user : users) if (condition.test(user)) result.add(user);
        return result;
    }

    // Generic mapper
    static <R> List<R> mapUsers(List<User> users, Function<User, R> mapper) {
        List<R> result = new ArrayList<>();
        for (User user : users) result.add(mapper.apply(user));
        return result;
    }

    public static void main(String[] args) {
        List<User> users = List.of(
            new User("Anna", 25),
            new User("Boris", 17),
            new User("Vika", 22)
        );

        // 1. Print all users
        processUsers(users, user -> System.out.println("User: " + user));

        // 2. Find only adults
        List<User> adults = filterUsers(users, user -> user.age >= 18);
        System.out.println("Adults: " + adults);

        // 3. Get adult names
        List<String> adultNames = mapUsers(adults, user -> user.name);
        System.out.println("Adult names: " + adultNames);

        // 4. Credit a bonus to adults
        processUsers(adults, user -> System.out.println(user.name + " received a bonus!"));
    }
}

Why is this better than the “ordinary” approach?

This approach gives you flexibility: the same methods can be used in very different scenarios by simply passing different functions. The code doesn’t grow into endless variants of “filter like this,” “print like that” — we have general-purpose tools that work everywhere. As a result, it’s more compact, clearer, and less error-prone. This style also fits perfectly with the modern Stream API, so when moving to streams you won’t have to learn anew — the approach is the same.

6. Common Mistakes When Passing Functions as Parameters

Error #1: The signature doesn’t match the expected interface.
If a method takes a Predicate<User> but you pass a lambda that returns not a boolean but, say, a String, the compiler will immediately say “uh-oh!” and refuse to build the project. Make sure the return type and parameters match what’s expected.

Error #2: The lambda captures variables that can change.
In Java, lambda expressions can use only final or effectively final variables from the outer context. If you try to modify such a variable inside the lambda, you’ll get a compilation error.

Error #3: Mixing up interfaces.
Sometimes you want to pass, for example, a Consumer<T>, but you accidentally write a function that returns something (for example, a Function<T, R>). Check that your lambda returns exactly what is needed (or nothing — for a Consumer).

Error #4: Lambdas that are too complex right in the argument list.
If a lambda takes more than one or two lines, it’s better to extract it into a separate variable or method. Otherwise, the code becomes unreadable, and you’ll be the only one who can make sense of it (and not always).

1
Task
JAVA 25 SELF, level 49, lesson 2
Locked
Animal Parade: Lining Up by Names 🐘
Animal Parade: Lining Up by Names 🐘
1
Task
JAVA 25 SELF, level 49, lesson 2
Locked
Report on "Star Monitoring" Metrics 🔭
Report on "Star Monitoring" Metrics 🔭
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION