Fundamentals 7 min read

Master Java Method References: Simplify Lambdas for Cleaner Code

This article explains Java's method reference feature, covering its four types, practical code examples for static methods, instance methods, constructors, and highlighting limitations compared to lambda expressions, helping developers write more readable and concise Java 8 code.

Programmer DD
Programmer DD
Programmer DD
Master Java Method References: Simplify Lambdas for Cleaner Code

1. Introduction

One of the most popular changes introduced in Java 8 is lambda expressions, which reduce boilerplate code and improve readability. Method references are a special form of lambda that refer to existing methods.

Method references include four types:

Static methods

Instance methods of a particular object

Instance methods of an arbitrary object of a particular type

Constructors

In this article we explore Java method references.

2. Referencing Static Methods

We start with a simple example that capitalizes and prints a list of strings:

List<String> messages = Arrays.asList("hello", "baeldung", "readers!");

Using a lambda:

messages.forEach(word -> StringUtils.capitalize(word));

Or using a method reference: messages.forEach(StringUtils::capitalize); Note the use of the :: operator.

3. Referencing an Instance Method of a Particular Object

We define two classes:

public class Bicycle {
    private String brand;
    private Integer frameSize;
    // standard constructor, getters and setters
}

public class BicycleComparator implements Comparator {
    @Override
    public int compare(Bicycle a, Bicycle b) {
        return a.getFrameSize().compareTo(b.getFrameSize());
    }
}

Create a comparator:

BicycleComparator bikeFrameSizeComparator = new BicycleComparator();

Using a lambda to sort:

createBicyclesList().stream()
    .sorted((a, b) -> bikeFrameSizeComparator.compare(a, b));

Using a method reference:

createBicyclesList().stream()
    .sorted(bikeFrameSizeComparator::compare);

4. Referencing an Instance Method of an Arbitrary Object of a Particular Type

We create a list of integers:

List<Integer> numbers = Arrays.asList(5, 3, 50, 24, 40, 2, 9, 18);

Lambda version:

numbers.stream()
    .sorted((a, b) -> a.compareTo(b));

Method reference version:

numbers.stream()
    .sorted(Integer::compareTo);

Method references make the code more readable.

5. Referencing Constructors

We add a new constructor to Bicycle that takes a brand string:

public Bicycle(String brand) {
    this.brand = brand;
    this.frameSize = 0;
}

Using a constructor reference to create an array of Bicycle objects from a list of brand strings:

List<String> bikeBrands = Arrays.asList("Giant", "Scott", "Trek", "GT");

Bicycle[] bikes = bikeBrands.stream()
    .map(Bicycle::new)
    .toArray(Bicycle[]::new);

6. Other Examples and Limitations

Method references are concise and improve readability, but they cannot replace every lambda expression because the output of the preceding expression must match the input parameters of the referenced method.

For example, a printf call requiring three arguments cannot be expressed as a method reference with forEach, which supplies only one argument.

We also show a no‑operation method that can be referenced from any lambda:

private static <T> void doNothingAtAll(Object... o) { }

createBicyclesList().forEach(o -> MethodReferenceExamples.doNothingAtAll(o));

7. Conclusion

This article covered Java method references, demonstrating how they can replace lambda expressions to produce clearer, more intention‑revealing code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javafunctional programmingJava 8Method References
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.