Java.Java8.What is a method reference?

🔎 What is a Method Reference?

A method reference is a compact, readable way to refer to an existing method by name rather than writing a full lambda.

It’s basically a lambda that just calls an existing method.


Basic Syntax

ClassName::methodName
// or
objectInstance::methodName

🔹 Types of Method References

TypeSyntaxExample
Reference to a static methodClassName::staticMethodMath::max
Reference to an instance method of a specific objectinstance::instanceMethodSystem.out::println
Reference to an instance method of an object of a particular typeClassName::instanceMethodString::toLowerCase
Reference to a constructorClassName::newArrayList::new

🧪 Examples

✅ 1. Static Method Reference

List<Integer> nums = Arrays.asList(3, 1, 2);
nums.sort(Integer::compare);  // equivalent to (a, b) -> Integer.compare(a, b)

✅ 2. Instance Method Reference of a Specific Object

PrintStream printer = System.out;
List<String> names = Arrays.asList("Alice", "Bob");
names.forEach(printer::println);  // instead of: name -> printer.println(name)

✅ 3. Instance Method Reference of Any Object of a Particular Type

List<String> words = Arrays.asList("Java", "is", "cool");
words.sort(String::compareToIgnoreCase);  // instead of (a, b) -> a.compareToIgnoreCase(b)

✅ 4. Constructor Reference

Supplier<List<String>> supplier = ArrayList::new;
List<String> list = supplier.get();  // Creates a new ArrayList

🧠 When to Use Method References?

  • When the lambda just calls an existing method
  • For cleaner, more expressive code
  • To improve readability in streams, filters, sorting, etc.

🔄 Lambda vs Method Reference Example

// Lambda
list.forEach(s -> System.out.println(s));

// Method reference
list.forEach(System.out::println);

Same result, but the second is more concise and readable.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.