The Wayback Machine - https://web.archive.org/web/20240917134458/https://www.geeksforgeeks.org/method-references-in-java-with-examples/
Open In App

Method References in Java with examples

Last Updated : 24 Feb, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Functional Interfaces in Java and Lambda Function are prerequisites required in order to grasp grip over method references in Java. As we all know that a method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In this article, we will see how to use methods as value. 

In Java 8 we can use the method as if they were objects or primitive values, and we can treat them as a variable. The example shows the function as a variable in java:

// This square function is a variable getSquare. 
Function<Integer, Integer> getSquare = i -> i * i; 
SomeFunction(a, b, getSquare); 
// Pass function as a argument to other function easily 

Sometimes, a lambda expression only calls an existing method. In those cases, it looks clear to refer to the existing method by name. The method references can do this, they are compact, easy-to-read as compared to lambda expressions. A method reference is the shorthand syntax for a lambda expression that contains just one method call. Here’s the general syntax of a 

Generic syntax: Method reference

A. To refer to a method in an object 

Object :: methodName 

B. To print all elements in a list

Following is an illustration of a lambda expression that just calls a single method in its entire execution: 

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

C. Shorthand to print all elements in a list 

To make the code clear and compact, In the above example, one can turn lambda expression into a method reference:

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

The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same. In general, one doesn’t have to pass arguments to method references.

The following example is about performing some operations on elements in the list and adding them. The operation to be performed on elements is a function argument and the caller can pass accordingly. 

Illustration:

public int transformAndAdd(List<Integer> l,
                           Function<Integer, Integer> ops) {
    int result = 0;
    for (Integer s : l)
        result += f.apply(s);

    return results;
}

// Operations utility class
class OpsUtil {

    // Method 1
    // To half the variable
    public static Integer doHalf(Integer x) {
        return x / 2;
    }

    // Method 2
    // Square up the integer number
    public static Integer doSquare(Integer x) {

        return x * x;
    }
    
    ... many more operations...
}

Following are the ways to call the above method as depicted below as follows:

List<Integer> list = new ArrayList<>();
// Add some element to list
...
// Using an anonymous class
transformAndAdd(list, new Function<Integer, Integer>() {
    public Integer apply(Integer i) {
        // The method
        return OpsUtil.doHalf(i);
    }
});

// Using a lambda expression
tranformAndAdd(list, i -> OpsUtil.doHalf(i));

// Using a method reference
tranformAndAdd(list, OpsUtil::doHalf);

Types of Method References 

There are four type method references that are as follows:

  1. Static Method Reference.
  2. Instance Method Reference of a particular object.
  3. Instance Method Reference of an arbitrary object of a particular type.
  4. Constructor Reference.

To look into all these types we will consider a common example of sorting with a comparator which is as follows:

Type 1: Reference to a static method

If a Lambda expression is like:

// If a lambda expression just call a static method of a class 
(args) -> Class.staticMethod(args)  

Then method reference is like:

// Shorthand if a lambda expression just call a static method of a class 
Class::staticMethod  

Example:

Java




// Java Program to Illustrate How One can use
// Static method reference
// To Sort with Custom Comparator
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Class 1
// Helper class
// Object need to be sorted
class Person {
 
    private String name;
    private Integer age;
 
    // Constructor
    public Person(String name, int age)
    {
        // This keyword refers to current instance itself
        this.name = name;
        this.age = age;
    }
 
    // Getter-setters
    public Integer getAge() { return age; }
    public String getName() { return name; }
}
 
// Class 2
// Main class
public class GFG {
 
    // Method 1
    // Static method to compare with name
    public static int compareByName(Person a, Person b)
    {
        return a.getName().compareTo(b.getName());
    }
 
    // Method 2
    // Static method to compare with age
    public static int compareByAge(Person a, Person b)
    {
        return a.getAge().compareTo(b.getAge());
    }
 
    // Method 3
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty ArrayList of user-defined type
        // List of person
        List<Person> personList = new ArrayList<>();
 
        // Adding elements to above List
        // using add() method
        personList.add(new Person("vicky", 24));
        personList.add(new Person("poonam", 25));
        personList.add(new Person("sachin", 19));
 
        // Using static method reference to
        // sort array by name
        Collections.sort(personList, GFG::compareByName);
 
        // Display message only
        System.out.println("Sort by name :");
 
        // Using streams over above object of Person type
        personList.stream()
            .map(x -> x.getName())
            .forEach(System.out::println);
 
        // Now using static method reference
        // to sort array by age
        Collections.sort(personList, GFG::compareByAge);
 
        // Display message only
        System.out.println("Sort by age :");
 
        // Using streams over above object of Person type
        personList.stream()
            .map(x -> x.getName())
            .forEach(System.out::println);
    }
}


Output: 

Sort by name :
poonam
sachin
vicky
Sort by age :
sachin
vicky
poonam

 

Type 2: Reference to an instance method of a particular object

If a Lambda expression is like:

// If a lambda expression just call a default method of an object 

(args) -> obj.instanceMethod(args) 

Then method reference is like:

// Shorthand if a lambda expression just call a default method of an object 

obj::instanceMethod 

Example:

Java




// Java Program to Illustrate How One can use
// Static method reference
// To Sort with Custom Comparator
// But using object method reference
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Class 1
// Helper class
// Object need to be sorted
class Person {
 
    // Attributes of a person
    private String name;
    private Integer age;
 
    // Constructor
    public Person(String name, int age)
    {
        // This keyword refers to current object itself
        this.name = name;
        this.age = age;
    }
 
    // Getter-setter methods
    public Integer getAge() { return age; }
    public String getName() { return name; }
}
 
// Class 2
// Helper class
// Comparator class
class ComparisonProvider {
 
    // Method 1
    // To compare with name
    public int compareByName(Person a, Person b)
    {
        return a.getName().compareTo(b.getName());
    }
 
    // Method 2
    // To compare with age
    public int compareByAge(Person a, Person b)
    {
        return a.getAge().compareTo(b.getAge());
    }
}
 
// Class 3
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty ArrayList of user-defined type
        // List of person
        List<Person> personList = new ArrayList<>();
 
        // Adding elements to above object
        // using add() method
        personList.add(new Person("vicky", 24));
        personList.add(new Person("poonam", 25));
        personList.add(new Person("sachin", 19));
 
        // A comparator class with multiple
        // comparator methods
        ComparisonProvider comparator
            = new ComparisonProvider();
 
        // Now using instance method reference
        // to sort array by name
        Collections.sort(personList,
                         comparator::compareByName);
 
        // Display message only
        System.out.println("Sort by name :");
 
        // Using streams
        personList.stream()
            .map(x -> x.getName())
            .forEach(System.out::println);
 
        // Using instance method reference
        // to sort array by age
        Collections.sort(personList,
                         comparator::compareByAge);
 
        // Display message only
        System.out.println("Sort by age :");
 
        personList.stream()
            .map(x -> x.getName())
            .forEach(System.out::println);
    }
}


Output: 

Sort by name :
poonam
sachin
vicky
Sort by age :
sachin
vicky
poonam

 

Type 3: Reference to an instance method of an arbitrary object of a particular type

If a Lambda expression is like:

// If a lambda expression just call an instance method of a  ObjectType 

(obj, args) -> obj.instanceMethod(args) 

Then method reference is like:

// Shorthand if a lambda expression just call an instance method of a ObjectType 

ObjectType::instanceMethod 

Example:

Java




// Java Program to Illustrate how One can use
// Instance type method reference to
// sort with custom comparator
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty ArrayList of user defined type
        // List of person
        List<String> personList = new ArrayList<>();
 
        // Adding elements to above object of List
        // using add() method
        personList.add("vicky");
        personList.add("poonam");
        personList.add("sachin");
 
        // Method reference to String type
        Collections.sort(personList,
                         String::compareToIgnoreCase);
 
        // Printing the elements(names) on console
        personList.forEach(System.out::println);
    }
}


Output: 

poonam
sachin
vicky

 

Type 4: Constructor method reference

If a Lambda expression is like: 

// If a lambda expression just create an object 
(args) -> new ClassName(args) 

Then method reference is like: 

// Shorthand if a lambda expression just create an object 
ClassName::new 

Example:

Java




// Java Program to Illustrate How We can Use
// constructor method reference
 
// Importing required classes
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.function.*;
 
// Object need to be sorted
class Person {
    private String name;
    private Integer age;
 
    // Constructor
    public Person()
    {
        Random ran = new Random();
 
        // Assigning a random value
        // to name
        this.name
            = ran
                  .ints(97, 122 + 1)
                  .limit(7)
                  .collect(StringBuilder::new,
                           StringBuilder::appendCodePoint,
                           StringBuilder::append)
                  .toString();
    }
 
    public Integer getAge()
    {
        return age;
    }
    public String getName()
    {
        return name;
    }
}
 
public class GFG {
 
    // Get List of objects of given
    // length and Supplier
    public static <T> List<T>
    getObjectList(int length,
                  Supplier<T> objectSupply)
    {
        List<T> list = new ArrayList<>();
 
        for (int i = 0; i < length; i++)
            list.add(objectSupply.get());
        return list;
    }
 
    public static void main(String[] args)
    {
 
        // Get 10 person by supplying
        // person supplier, Supplier is
        // created by person constructor
        // reference
        List<Person> personList
            = getObjectList(5, Person::new);
 
        // Print names of personList
        personList.stream()
            .map(x -> x.getName())
            .forEach(System.out::println);
    }
}


Output: 

vzskgmu
iupltfx
kocsipj
lyvhxsp
hbdphyv

 

Conclusion: As mentioned above, if a lambda expression only calls an existing method then using method reference can make code more readable and clear. There are many more things we can do with Java8 Lambda and Method References while using Java streams.



Previous Article
Next Article

Similar Reads

Difference Between Equality of Objects and Equality of References in Java
Equality of objects means when two separate objects happen to have the same values/state. Whereas equality of references means when two object references point to the same object. The == operator can be used to check if two object references point to the same object. To be able to compare two java objects of the same class the boolean equals(Object
2 min read
Types of References in Java
In Java there are four types of references differentiated on the way by which they are garbage collected. Strong References Weak References Soft References Phantom References Prerequisite: Garbage Collection Strong References: This is the default type/class of Reference Object. Any object which has an active strong reference are not eligible for ga
4 min read
C/C++ Pointers vs Java References
Java doesn't have pointers; Java has references. Reference: A reference is a variable that refers to something else and can be used as an alias for that something else. Pointer: A pointer is a variable that stores a memory address, for the purpose of acting as an alias to what is stored at that address. So, a pointer is a reference, but a reference
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
Java Clock tickMinutes() method in Java with Examples
java.time.Clock.tickMinutes(ZoneId zone) method is a static method of Clock class that returns the current instant ticking in whole minutes using the best available system clock and the time-zone of that instant is same as the time-zone passed as a parameter. Nanosecond and second fields of the clock are set to zero to round the instant in the whol
3 min read
Java Clock withZone() method in Java with Examples
The java.time.Clock.withZone(ZoneId zone) method is a method of Clock class which returns a clock copy of clock object on which this method is applied, with a different time-zone. If there is a clock and it is required to change the zone of clock but not other properties, then withZone() method is used. This method takes zone as parameter which is
3 min read
Java.lang.Short toString() method in Java with Examples
toString(short) The static toString() method of java.lang.Short returns a new String object representing the specified short. The radix is assumed to be 10.This is a static method hence no object of Short class is required for calling this method. Syntax: public static String toString(short b) Parameters: This method accepts a parameter b which is
2 min read
Java.util.Collections.rotate() Method in Java with Examples
java.util.Collections.rotate() method is present in java.util.Collections class. It is used to rotate the elements present in the specified list of Collection by a given distance. Syntax: public static void rotate(List&lt; type &gt; list, int distance) Parameters : list - the list to be rotated. distance - the distance to rotate the list. type - Ty
2 min read
Java.util.Collections.disjoint() Method in java with Examples
java.util.Collections.disjoint() method is present in java.util.Collections class. It is used to check whether two specified collections are disjoint or not. More formally, two collections are disjoint if they have no elements in common. Syntax: public static boolean disjoint(Collection&lt;?&gt; c1, Collection&lt;?&gt; c2) Parameters : c1 - a colle
3 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java 8 | IntToDoubleFunction Interface in Java with Examples
The IntToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and gives a double-valued result. The lambda expression assigned to an object of IntToDoubleFunction type is used to define
1 min read
Java 8 | DoubleToLongFunction Interface in Java with Examples
The DoubleToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an long-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to defi
1 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Java.util.function.BiPredicate interface in Java with Examples
The BiPredicate&lt;T, V&gt; interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on two objects and returns a predicate value based on that condition. It is a functional interface and thus can be used in lambda expression also. public interface BiPredicate&lt;T, V&gt; Methods: test(): This functio
2 min read
Java.util.function.DoublePredicate interface in Java with Examples
The DoublePredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a Double object and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface DoublePredicate Methods test(): This function evaluates a co
2 min read
Java.util.function.LongPredicate interface in Java with Examples
The LongPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a long value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface LongPredicate Methods test(): This function evaluates a condition
2 min read
Java.util.function.IntPredicate interface in Java with Examples
The IntPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on an integer value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface IntPredicate Methods: test(): This function evaluates a condit
2 min read
Java IO : Input-output in Java with Examples
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations. Before exploring various input and output streams lets look at 3 standard or default streams that Java has to provide
7 min read
Java class dependency analyzer in Java 8 with Examples
Java class dependency analyzer: jdeps is a new command-line tool introduced in JDK 8 to understand the static dependencies and libraries of application i.e. jdeps command shows the package-level or class-level dependencies of Java class files. The input for jdeps can be a .class file pathname, a JAR file or it can be a fully qualified class name to
2 min read
Java Deprecated API Scanner tool (jdepscan) in Java 9 with Examples
Java Deprecated API Scanner tool: Java Deprecated API Scanner tool i.e. jdeprscan is a static analyzing command-line tool which is introduced in JDK 9 for find out the uses of deprecated API in the given input. Here the input can be .class file name, directory or JAR file. Whenever we provide any input to jdeprscan command line tool then it generat
2 min read
java.lang.ArrayIndexOutOfBoundsExcepiton in Java with Examples
The java.lang.ArrayIndexOutOfBoundsException is a runtime exception and thrown only at the execution state of the program. Java compiler never checks for this error during compilation. The java.lang.ArrayIndexOutOfBoundsException is one of the most common exceptions in java. It occurs when the programmer tries to access the value of an element in a
2 min read
java.net.BindException in Java with Examples
The java.net.BindException is an exception that is thrown when there is an error caused in binding when an application tries to bind a socket to a local address and port. Mostly, this may occur due to 2 reasons, either the port is already in use(due to another application) or the address requested just cannot be assigned to this application. The Bi
2 min read
Article Tags :
Practice Tags :