Fun 2-minutes Concept : Method References
Java 8 is a gift that keeps on giving.
Hi! General wonderment but how many of us really use all the new features of Java. Do we sometimes learn these features and go back and re-write our code? Let me know in comments :)
What are Method References?
Method references are a shorthand notation for calling a method via a lambda expression. They make your code cleaner and more readable by allowing you to refer to methods directly.
How Do They Work?
A method reference is a compact and readable way to handle functional interfaces, which are interfaces with a single abstract method. Instead of writing a lambda expression like this:
list.forEach(item -> System.out.println(item));You can use a method reference to achieve the same result:
list.forEach(System.out::println);Get Full Stack Developer’s stories in your inbox
Join Medium for free to get updates from this writer.
Types of Method References:
- Reference to a static method:
// Static method reference
Function<Integer, String> intToString = String::valueOf;2. Reference to an instance method of a particular object:
// Instance method reference of a particular object
Consumer<String> print = System.out::println;3. Reference to an instance method of an arbitrary object of a particular type:
// Instance method reference of an arbitrary object
Function<String, String> toUpperCase = String::toUpperCase;4. Reference to a constructor:
// Constructor reference
Supplier<List<String>> listSupplier = ArrayList::new;Why Is It Fun?
- Expressive and Concise: Method references make the code more concise and easier to understand.
- Functional Programming: It introduces a functional style, making Java programming more modern and expressive.
- Less Boilerplate: Reduces the boilerplate code, making it more enjoyable to write and read.
Using method references can feel a bit like you’re giving Java a more human-like understanding of what you’re trying to accomplish, which can be quite satisfying!







