$show=/label

Java 8 Method References With Examples

SHARE:

A quick and practical guide to method references in java 8 with example programs. This is a new concept that is a replacement to Lambda expression for quick and only for method calls.

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.


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Method References With Examples
Java 8 Method References With Examples
A quick and practical guide to method references in java 8 with example programs. This is a new concept that is a replacement to Lambda expression for quick and only for method calls.
https://1.bp.blogspot.com/-Qjho0IxiV4g/XgohZbni6lI/AAAAAAAACH4/D-LDnbJMs4wy6n3sdw8QeVFOlxBWXn42wCLcBGAsYHQ/s640/Java%2B8%2BMethod%2BReferences%2BWith%2BExamples.png
https://1.bp.blogspot.com/-Qjho0IxiV4g/XgohZbni6lI/AAAAAAAACH4/D-LDnbJMs4wy6n3sdw8QeVFOlxBWXn42wCLcBGAsYHQ/s72-c/Java%2B8%2BMethod%2BReferences%2BWith%2BExamples.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/12/java-8-method-references.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/12/java-8-method-references.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content