Java method reference to an instance method of an arbitrary object of a particular type

This source code example demonstrates the usage of the Java method reference to an instance method of an arbitrary object of a particular type.

Well, a Java method reference to an instance method of an arbitrary object of a particular type is a type of method reference introduced in Java 8.

Sometimes, we call a method of argument in the lambda expression. In that case, we can use a method reference to call an instance method of an arbitrary object of a specific type.

Syntax :

ContainingType::methodName

Java method reference to an instance method of an arbitrary object of a particular type example

package com.java.lambda.methodref;

import java.util.*;
import java.util.function.Function;

public class MethodReferencesDemo {

    public static void main(String[] args) {

        // 3. Reference to the instance method of an arbitrary object
        // Sometimes, we call a method of argument in the lambda expression.
        // In that case, we can use a method reference to call an instance
        // method of an arbitrary object of a specific type.

        Function<String, String> stringFunction = (String input) -> input.toLowerCase();
        System.out.println(stringFunction.apply("Java Guides"));

        // using method reference
        Function<String, String> stringFunctionMethodRef = String::toLowerCase;
        System.out.println(stringFunctionMethodRef.apply("Java Guides"));

        String[] strArray = { "A", "E", "I", "O", "U", "a", "e", "i", "o", "u" };

        // using lambda
        Arrays.sort(strArray, (s1, s2) -> s1.compareToIgnoreCase(s2));

        // using method reference
        Arrays.sort(strArray, String::compareToIgnoreCase);
    }
}

Output:

java guides
java guides

In the below lambda expression, we are calling a method of lambda expression argument:

        Function<String, String> stringFunction = (String input) -> input.toLowerCase();
        System.out.println(stringFunction.apply("Java Guides"));

So, we can replace above lambda expression with a method reference:

        // using method reference
        Function<String, String> stringFunctionMethodRef = String::toLowerCase;
        System.out.println(stringFunctionMethodRef.apply("Java Guides"));

One more example:

        String[] strArray = { "A", "E", "I", "O", "U", "a", "e", "i", "o", "u" };

        // using lambda
        Arrays.sort(strArray, (s1, s2) -> s1.compareToIgnoreCase(s2));

        // using method reference
        Arrays.sort(strArray, String::compareToIgnoreCase);

Related Source Code Examples


Comments