Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Monday, December 30, 2019

Java 8 Method References With Examples

1. Overview


In this tutorial, We'll learn how to use Method References in Java 8 and where we can use Method References in the programs. To understand this article, you should have a minimal understanding of Lambda Expressions.

Read: Introduction to Lambda Expressions in Java 8

Method References are part of the new Java 8 concept and used to refer to the functional method of Functional Interface. Syntax is ClassName::methodName. Method ref is indicated with "::" - double colon operator. This is a compact and simple form of the lambda expression. If you are using a lambda expression to refer only functional method and not any additional logic then it is best to use method references in these kinds of scenarios.

We'll learn types of method references and their example programs.

Java 8 Method References With Examples




2. Types of Method References


Java 8 introduced typically with 4 types of Method References. The following are the types and will write example programs on each type.

A) Reference to a Static Method
B) Reference to instance method from instance - ClassInstance::instanceMethodName
C) Reference to instance method from class type - Class::instanceMethodName
D) Reference to constructor - Class::new

3. Reference to a Static Method


Example 1: Using Supplier Functional Interface


In the below example program, we have used Supplier FI and its functional method which does not take any value and returns a value.


package com.javaprogramto.w3schools.programs.java8.method.reference;

import java.util.function.Supplier;

/**
 * 
 * Static Method Reference Example
 * 
 * @author JavaProgramTo.com
 *
 */
public class StaticMethodReference {

    public static void main(String[] args) {

        Supplier i = StaticMethodReference::print;
        int value = (int) i.get();
        System.out.println("returned value : " + value);

    }

    public static int print() {
        System.out.println("Static method ref.");
        return 1;
    }

}

Output:


Static method ref.
returned value : 1

Example 2: Using custom Functional Interface


Created a Custom FI with process() functional method with no parameters and return type. So, we can assign the print() method to CustomFI. In the below example, assigned StaticMethodReference2::print method to the CustomFI ref. That means mapping print() method to process() method. So, When we call customFI.process() then its underlying method print() will be executed.

package com.javaprogramto.w3schools.programs.java8.method.reference;

import java.util.function.Supplier;

/**
 * 
 * Static Method Reference Example 2
 * 
 * @author JavaProgramTo.com
 *
 */
 
@FunctionalInterface 
interface CustomFI {

    void process();
}

public class StaticMethodReference2 {

    public static void main(String[] args) {

        CustomFI customFI = StaticMethodReference2::print;
        customFI.process();

    }

    public static void print() {
        System.out.println("Static method ref example 2.");
    }

}

Output:

Static method ref example 2.

Example 3: 


Static method reference to find the sum of two numbers. Here, we used BiFunction to hold the ref of the Static Method Reference. When BiFunction apply(10, 20) method is called then addition(10, 20) method will be executed and values also will be passed to the addition method from the apply method.


package com.javaprogramto.w3schools.programs.java8.method.reference;

import java.util.function.BiFunction;

/**
 * 
 * Static Method Reference Example with addition formulae
 * 
 * @author JavaProgramTo.com
 *
 */

public class StaticMethodReference2 {

    public static void main(String[] args) {

        BiFunction customFI = StaticMethodReference2::addition;
        int sum = customFI.apply(10, 20);
        System.out.println("Addition : " + sum);

    }

    public static int addition(int a, int b) {
        return a + b;
    }

}

Output:

Addition : 30

4. Reference to instance method from instance - ClassInstance::instanceMethodName


The below program demonstrates how to use a class instance with method reference. This is similar to the static method ref but here we need to create the instance first then use a double colon :: on the instance like classInstanceMethodReference::addition;.


package com.javaprogramto.w3schools.programs.java8.method.reference;

import java.util.function.BiFunction;

/**
 * 
 * Class Instance Method Reference Example with addition formulae
 * 
 * @author JavaProgramTo.com
 *
 */

public class ClassInstanceMethodReference {

    public static void main(String[] args) {

        ClassInstanceMethodReference classInstanceMethodReference = new ClassInstanceMethodReference();

        BiFunction customFI = classInstanceMethodReference::addition;
        int sum = customFI.apply(10, 20);
        System.out.println("Addition : " + sum);

    }

    public int addition(int a, int b) {
        return a + b;
    }

}

Output:


Addition : 30

5) Reference to instance method from class type - Class::instanceMethodName


This is to where ever we use the method on two Strings or two same type objects. For example, s1.compareTo(s2) can be rewritten as String::compareTo.

Example program to sort strings.

package com.javaprogramto.w3schools.programs.java8.method.reference;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MethodReferenceFromClassInstance {

    public static void main(String[] args) {
        List strings = Arrays.asList("java", "program", "to", "com", "java-w3schools", "blog", "core java",
                "JavaProgramTo.com");

        // without method ref.
        List sorted = strings.stream().sorted((s1, s2) -> s1.compareTo(s2)).collect(Collectors.toList());

        System.out.println(sorted);

        // with method ref.
        List sortedAlt = strings.stream().sorted(String::compareTo).collect(Collectors.toList());

        System.out.println(sortedAlt);
    }

}

Output:

[JavaProgramTo.com, blog, com, core java, java, java-w3schools, program, to]
[JavaProgramTo.com, blog, com, core java, java, java-w3schools, program, to]


6) Reference to constructor - Class::new


As of now, we have seen how to access the instance and static methods using method reference. But you have a question that is it possible for constructors?
Yes, It is allowed in Java to use :: to invoke the constructor.

process(new ArrayList()) can be simplified as process(ArrayList::new);

ArrayList::new calls the constructor to create the ArrayList instance.

Creating a list of numbers from range 1 to 100 by creating ArrayList object using method ref.

List integers = IntStream
                .range(1, 100)
                .boxed()
                .collect(Collectors.toCollection( ArrayList::new ));



7. Conclusion


In this article, We've seen the following.

A) what is Method Reference?
B) why it is introduced?
C) what is the advantage? 
D) Where to use?

Example program on each type of Method Reference.

Math class has many static methods so we can use all of them with static method reference such as Math::max, Math::min, Math::pow
Where ever Reduce FI is needed there you can use the static method reference.


No comments:

Post a Comment

Please do not add any spam links in the comments section.