Java 8
Method References
Supplier Interface
Parameterized Result
Programming Concepts

Java 8 method references provide a Supplier capable of supplying a parameterized result

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Method references in Java 8 are a powerful feature that allow you to express instances of functional interfaces (an interface with a single abstract method) more concisely. Method references help to point to methods by their names rather than providing a delegate method. This can lead to more readable and reusable code.

Understanding Method References

Method references are syntactic sugar in Java, and they can be used to refer directly to a method without executing it. When a lambda expression does nothing but call an existing method, a method reference might simplify the code. The general syntax of a method reference is:

 
ObjectOrClassName::methodName

There are four kinds of method references:

  1. Reference to a static method: ContainingClass::staticMethodName
  2. Reference to an instance method of a particular object: containingObject::instanceMethodName
  3. Reference to an instance method of an arbitrary object of a particular type: ContainingType::methodName
  4. Reference to a constructor: ClassName::new

Supplier Interface with Parameterized Result

The Supplier<T> interface is a functional interface that provides a get() method which takes no input and returns a result. Often used for lazy generation of values, it is a fundamental part of Java's functional programming capabilities introduced in Java 8.

Suppose you have a scenario where you need a Supplier to provide configuration settings. Instead of writing a full lambda expression, you can leverage method references to make your code cleaner. Here’s an example:

java
1class ConfigSettings {
2    private String databaseUrl;
3
4    public ConfigSettings(String databaseUrl) {
5        this.databaseUrl = databaseUrl;
6    }
7
8    public String getDatabaseUrl() {
9        return databaseUrl;
10    }
11}
12
13public class Application {
14    public static void main(String[] args) {
15        ConfigSettings settings = new ConfigSettings("jdbc:mysql://localhost:3306/mydb");
16        Supplier<String> dbUrlSupplier = settings::getDatabaseUrl;
17        System.out.println("Database URL: " + dbUrlSupplier.get());
18    }
19}

In this example, dbUrlSupplier is a Supplier<String> type that uses a method reference to settings::getDatabaseUrl. This points to the getDatabaseUrl method of a ConfigSettings instance.

Advantages of Using Method References

Method references help to achieve cleaner and more readable code. They also reduce the boilerplate associated with anonymous classes and provide a clear link between the functional interface method and the underlying method implementation.

When to Use Method References

It's most practical to use method references when:

  • The lambda expression is directly referring to a method by name.
  • You are not performing any operations on the method's results before returning them or passing them to another method.

Using method references can make constructs such as Streams API operations more succinct and visually intuitive. For example, consider a situation where you need to transform or filter a list of objects. Using method references with Streams can make your pipeline of operations very expressive and clean.

Comparison Table

FeatureLambda ExpressionMethod Reference
Syntax(args) -> ClassName.staticMethod(args)ClassName::staticMethod
ContextCan use external variables within lambda scopeOnly direct reference to method
Use CaseComplex operations, requiring arguments manipulationDirect invocation of a method
Visual ClarityLess clear when method calls are simpleMore intuitive with simple method calls

Conclusion

Java 8 method references are not only a tool for reducing the verbosity of your code but also aid in making the intention of your code clearer at a glance. They serve as a bridge between the imperative and functional programming paradigms in Java. By effectively using method references, Java developers can write more expressive and modular code that is easier to read and maintain.

In summary, method references can drastically reduce the amount of code and improve readability, making them a valuable addition to the Java programmer's toolkit, especially when used in conjunction with functional interfaces like Supplier in Java 8.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions