πŸ”§ What is a Method Reference?

AΒ Method Reference is a shorthand syntax for calling a method via a lambda expression, using the :: operator.

βœ… It helps make your code more concise and readable when the lambda simply calls a method.


🧠 General Syntax

ClassName::methodName

Instead of:

x -> ClassName.methodName(x)

🧩 Types of Method References

Type Syntax Example Use Case Example
1️⃣ Static Method ClassName::staticMethod Integer::parseInt
2️⃣ Instance Method (of a specific object) obj::instanceMethod System.out::println
3️⃣ Instance Method (of arbitrary object of a class) ClassName::instanceMethod String::toLowerCase
4️⃣ Constructor Reference ClassName::new ArrayList::new

βœ… Examples

1. Static Method Reference

Function<String, Integer> toInt = Integer::parseInt;

System.out.println(toInt.apply("123")); Β // Output: 123


2. Instance Method of a Particular Object

List<String> names = Arrays.asList("Aftab", "Neha", "Ravi");

names.forEach(System.out::println); Β // Equivalent to: names.forEach(name -> System.out.println(name))


3. Instance Method of Arbitrary Object

List<String> names = Arrays.asList("aftab", "neha", "ravi");

names.stream()
Β  Β  Β .map(String::toUpperCase) Β  Β  Β // Equivalent to: name -> name.toUpperCase()
Β  Β  Β .forEach(System.out::println);

Β 


4. Constructor Reference

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

List<String> list = listSupplier.get();


🎯 When to Use

Use :: only when the lambda expression:

  • Only calls a method
  • Doesn’t need to modify arguments
  • Keeps code clean and expressive

πŸ”š Summary

Feature Value
Symbol :: (double colon)
Purpose Shortens lambda expressions
Introduced In Java 8
Works With Lambdas, Streams, Functional Interfaces
Readability βœ… Improves
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.