Java.Core.What are method references in Java? How are they used?

🌐 What are Method References?

A method reference is a shortcut (syntactic sugar) that lets you refer to a method directly — instead of writing a full lambda expression. You can use method references wherever a functional interface is expected.


🔗 Why Use Method References?

✅ They make the code shorter and more readable.
✅ They reuse existing methods instead of rewriting them inside a lambda.
✅ They work beautifully with Streams, functional programming, and lambdas.


💡 Example: Printing a List

✅ Using Lambda

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

✅ Using Method Reference (Cleaner)

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

System.out::println is a method reference to println.

It’s shorthand for name -> System.out.println(name).

📚 Types of Method References

TypeSyntaxExample
Static methodClassName::methodNameMath::max
Instance method on specific objectinstance::methodNameSystem.out::println
Instance method on arbitrary object of a typeClassName::methodNameString::toUpperCase
Constructor referenceClassName::newArrayList::new

📖 Examples

1️⃣ Static Method Reference

Function<Integer, String> converter = String::valueOf;
// Equivalent to: (num) -> String.valueOf(num)

2️⃣ Instance Method Reference (on specific object)

String prefix = "Hello, ";
Function<String, String> greeter = prefix::concat;
// Equivalent to: name -> prefix.concat(name)

3️⃣ Instance Method Reference (on arbitrary object of a type)

List<String> names = List.of("Alice", "Bob", "Charlie");
names.stream()
     .map(String::toUpperCase)    // Equivalent to: name -> name.toUpperCase()
     .forEach(System.out::println);

4️⃣ Constructor Reference

Supplier<List<String>> supplier = ArrayList::new;
// Equivalent to: () -> new ArrayList<String>()

⚙️ Where are Method References Used?

Streams (map, filter, forEach, etc.)
Callbacks
Functional Interfaces (Consumer, Supplier, Function, Comparator, etc.)


🧰 Real-World Example: Sorting a List

Lambda

List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
names.sort((a, b) -> a.compareToIgnoreCase(b));

Method Reference

names.sort(String::compareToIgnoreCase);

⚡ When to Use Method References?

SituationUse
Calling a single existing method directly✅ Method Reference
Need more complex logic (conditions, loops)❌ Use Lambda

📊 Summary Table

FeatureLambda ExpressionMethod Reference
FlexibilityAny code blockDirect method call only
ReadabilityVerbose for simple casesVery clean
PerformanceSameSame
Examplex -> x.toUpperCase()String::toUpperCase

🎯 Final Pro Tip

✅ Method references are just shortcuts for lambdas that call existing methods.
✅ They work only when method signature matches functional interface signature.
✅ They make your code more concise and readable, especially with streams.

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