Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Types of Method References
2.1.
Reference to a Static Method
2.2.
Reference to an Instance Method of a Particular Object
2.3.
Reference to a Constructor
3.
Frequently Asked Questions
3.1.
What is a method reference in Java 8?
3.2.
Can we use method references with any method?
3.3.
Are method references more efficient than lambda expressions?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Method Reference in Java 8

Author Rinki Deka
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Java 8 introduced a variety of features that significantly eased the way developers write code, making it more readable & efficient. Method references, a part of this update, are a notable addition, allowing methods to be used as lambdas. 

Method Reference in Java 8

This article is designed to guide you through the concept of method references, their types, & practical applications in Java 8. By the end of this article, you'll have a firm understanding of this feature & how to implement it in your coding projects.

Let's begin our exploration into the world of Java 8's method references.

Types of Method References

Method references in Java 8 are a shorthand notation of a lambda expression to call a method. We'll explore the three main types of method references, providing examples & explanations for each.

Reference to a Static Method

Static method references are used when a lambda expression calls a static method. Here’s the syntax:

ClassName::staticMethodName


Let's consider an example. Suppose we have a utility class with a static method to check if a number is prime:

public class Util {
    public static boolean isPrime(int number) {
        // method logic
    }
}
List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 7, 11, 13);
numbers.stream().filter(Util::isPrime).forEach(System.out::println);


In this example, Util::isPrime is a method reference that points to the static method isPrime in Util class. It’s an alternative to the lambda expression (number) -> Util.isPrime(number).

Reference to an Instance Method of a Particular Object

Instance method references are about methods of a particular object. The syntax looks like:

instance::instanceMethodName


For instance, let's say we have a String list and we want to convert each element to uppercase:

List<String> words = Arrays.asList("Java", "Stream", "Method", "Reference");
words.stream().map(String::toUpperCase).forEach(System.out::println);


Here, String::toUpperCase refers to the toUpperCase method of the String class. This method reference is equivalent to the lambda expression (word) -> word.toUpperCase().

Reference to a Constructor

Constructor references are used to reference a constructor of a class. The syntax for this is:

ClassName::new
Consider we have a class Person:

public class Person {
    String name;

 Person(String name) {
        this.name = name;
    }
}
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<Person> people = names.stream().map(Person::new).collect(Collectors.toList());


In this code snippet, Person::new is a constructor reference which creates a new instance of Person for each element in the names list.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

What is a method reference in Java 8?

A method reference is a shorthand notation of a lambda expression to call a method.

Can we use method references with any method?

Yes, as long as the method's arguments match the functional interface's abstract method.

Are method references more efficient than lambda expressions?

They are generally more readable & can be more efficient due to improved code reuse.

Conclusion

Method references in Java 8 are a powerful feature that not only simplifies the syntax but also enhances code readability & maintainability. Understanding & implementing these references can greatly improve your coding efficiency & style. As you delve into more complex Java projects, these skills will undoubtedly prove invaluable. Keep practicing & exploring to fully leverage the potential of Java 8!

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Math Functions in Java
Next article
OOPS Concepts in Java
Live masterclass