lambda expressions
method references
Java programming
functional interfaces
Java 8 features

Lambda expression vs method reference

Interview Questions practice on Codemia

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

Browse interview questions

Lambda expressions and method references are two constructs available in Java to streamline functional programming. They were both introduced in Java 8 and have become integral in writing clean, efficient, and readable code. Despite their similarities, they provide solutions to slightly different programming scenarios.

Introduction to Lambda Expressions

Lambda expressions in Java are a clear and concise way of representing a functional interface. Essentially, they allow for the implementation of abstract methods of a functional interface in a single line, making the code more expressive and less verbose than traditional anonymous classes.

Basic Syntax

A lambda expression consists of three components:

  • A set of parameters
  • An arrow token (->)
  • A body containing the statements
java
(parameters) -> { statements }

For example, consider a simple use case for a lambda expression with a functional interface:

java
FunctionalInterface<Integer, Integer> increment = (x) -> x + 1;
System.out.println(increment.apply(5)); // Outputs 6

Key Features

  • Conciseness: Eliminates boilerplate code.
  • Readability: Makes code flow easier to trace.
  • Compatibility: Can be used anywhere a functional interface is used.

Exploring Method References

Method references are shorthand for lambda expressions that simply call a method. They are used when a lambda expression merely forwards its parameters to an existing method. Method references require a compatible target with the method's signature from the functional interface.

Forms of Method References

There are four types of method references:

  1. Reference to a static method:
java
   ClassName::staticMethodName

Example:

java
   Function<String, Integer> parseInt = Integer::parseInt;
  1. Reference to an instance method of a particular object:
java
   instance::instanceMethodName

Example:

java
   Object obj = new Object();
   Supplier<String> toStringSupplier = obj::toString;
  1. Reference to an instance method of an arbitrary object of a particular type:
java
   ClassName::instanceMethodName

Example:

java
   Function<String, String> toUpperCase = String::toUpperCase;
  1. Reference to a constructor:
java
   ClassName::new

Example:

java
   Supplier<List<String>> listSupplier = ArrayList::new;

Advantages

  • Clarity: Further reduces boilerplate, especially when the lambda was only going to call another method.
  • Reusability: Method references can automatically adapt to the signature of the target functional interface.

Lambda Expressions vs Method References: Key Differences

  • Syntax and Usage: While lambda expressions specify a method directly with parameters and a function body, method references refer to methods by name and can be more concise if a lambda just forwards its parameters.
  • Readability: Method references often improve readability and succinctness; however, overly using them in complex scenarios can detract from the understanding of the code flow.
  • Use Cases: Lambda expressions offer the flexibility to include more than a single line of logic, while method references are preferred for directly invoking existing methods.

Example Comparison

A quick example illustrating both can demonstrate when one could be preferable over the other:

Lambda Expression Example:

java
List<String> names = List.of("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));

Equivalent Method Reference Example:

java
names.forEach(System.out::println);

Summary Table

AspectLambda ExpressionMethod Reference
Syntax(parameters) -> &#123;expression/body&#125;ClassName::methodName
Use CasesMulti-line logic, straightforward implementationsCall existing methods with same parameter set
ReadabilityCan become verbose if overusedUsually clearer for simple operations
FlexibilityAllows additional logic instead of direct callLimited to forwarding parameters

Conclusion

The choice between lambda expressions and method references often depends on the complexity and context of the task. Understanding both allows developers to write Java code that is both expressive and clean. By embracing these constructs, Java’s embrace of functional programming paradigms makes programs compact and maintains high readability levels.


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

All Rights Reserved.