• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Java Method Reference – Static, Instance, Arbitrary Object & Constructor Reference

November 23, 2020 by javainterviewpoint Leave a Comment

In this article, we will look at Java method reference and its types – Static method reference, Instance method reference, Arbitrary object reference, and Constructor Reference.

The method reference is nothing but the simplified version of the lambda expression. Instead of providing an implementation body, a method reference refers to an existing available method.

Java Method Reference

Java Method Reference 2
To start with, let’s take a look at a simple lambda expression and how it can be re-written using method reference.

Let’s iterate a simple list; the forEach() method of the Iterable class takes the Consumer as a parameter.

List players = new ArrayList();
players.add("Zidane");
players.add("Roger");
players.add("Tiger");
players.add("Walsh");

players.forEach(p -> System.out.println(p));

We can change the above lambda to method reference like below.

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

The double colon (::) operator specifies a method reference; it provides the reference to the println method. The key point to be noted is that we don’t need to specify the parenthesis () for the method.

 Advantages of Method Reference

  1. It is shorter than a lambda expression
  2. It includes the name of the class, which contains the method; this improves the readability of the code.

Types of Method Reference

There are four types of method references available

  1. Static Method Reference
  2. Instance Method Reference
  3. Arbitrary object – Instance Method Reference
  4. Constructor Reference

Types of Method Reference

1. Static Method Reference:

Static Method Reference is nothing but using the class name to call the static method and the Syntax for is

ClassName::StaticMethodName

For Example, Suppose we have a list of integers, and we need to find the square root of each element, then we can simply use the static method sqrt() present in the Math class.

List integerList = new ArrayList();
integerList.add(4);
integerList.add(9);
integerList.add(16);
integerList.add(25);

integerList.stream().map(Math::sqrt).forEach(System.out::println);

The method reference Math::sqrt refers to that method as the implementation of the Function interface. The above code is equivalent to the below lambda expression.

integerList.stream().map(i -> Math.sqrt(i)).forEach(i -> System.out.println(i));

Rather than using the predefined classes and methods, let’s use our class and use static method reference in it.

import java.util.function.Function;

class Welcome
{
   public static String greetMessage(String message)
   {
      return "Welcome " + message;
   }
}

public class Greeting
{
   public static void main(String[] args)
   {
      Function<String, String> message = Welcome::greetMessage;
      System.out.println(message.apply("JavaInterviewpoint"));
   }
}

The Welcome class has the static method greetMessage, We can simply call it using Welcome::greetMessage

2. Instance Method Reference

Even in the previous code snippet, we have used Instance method reference.

System.out::println

Where out is the object of PrintStream class present in the System class, the context will supply the arguments to the method.

Let’s call the sumOfNumber method using the instance method reference

package com.javainterviewpoint;

import java.util.function.BiFunction;

class Sum
{
   public int sumOfNumbers(int a, int b)
   {
      return a + b;
   }
}

public class Addition
{
   public static void main(String[] args)
   {
      Sum s = new Sum();
      BiFunction<Integer, Integer, Integer> add = s::sumOfNumbers;
      System.out.println(add.apply(10, 20));
   }
}

3. Arbitrary object Reference

Arbitrary object Instance method reference is one of the most commonly used method references, and we can call the instance method of the class using the class name directly.

Syntax: ClassName::InstanceMethodName

For example, if we want to convert a string to uppercase, then we can use the toUpperCase() method of the String class.

String value = "hello";
Stream.of(value).map(String::toUpperCase).forEach(System.out::println);

The equivalent lambda expression would be

Stream.of(value).map(v -> v.toUpperCase()).forEach(v -> System.out.println(v));

Let’s try to sort out the elements of a list

package com.javainterviewpoint;

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

public class Sort
{
   public static void main(String[] args)
   {
      List userList = Arrays.asList("Jones", "Alice", "Andy", "Zidane",
            "Bob");
      List sortedUserList = userList.stream()
            .sorted(String::compareToIgnoreCase).collect(Collectors.toList());
      System.out.println(sortedUserList);
   }
}

4. Constructor Reference

Constructor Reference is one of the most useful method references. It enables us to instantiate an object using a method reference as part of a stream.

Before getting into the details, let’s start with a simple scenario

Say for example, if we have a list of Students and we need the list of student name only, then we can use either of the below approaches

package com.javainterviewpoint;

public class Student
{
   private int id;
   private String name;

   public Student()
   {
      super();
   }
   public Student(String name)
   {
      super();
      this.name = name;
   }

   public int getId()
   {
      return id;
   }
   public void setId(int id)
   {
      this.id = id;
   }

   public String getName()
   {
      return name;
   }
   public void setName(String name)
   {
      this.name = name;
   }
}

List studentList = new ArrayList();
Student s1 = new Student(1, "Bob");
Student s2 = new Student(2, "Alice");
studentList.add(s1);
studentList.add(s2);

List studentNames = studentList.stream().map(Student::getName)
     .collect(Collectors.toList());

or we can use lambda expressions

List studentNames = studentList.stream().map(s -> s.getName())
   .collect(Collectors.toList());

What if we need the other way around? What if we have a list of String and we need a list of Student objects?
We can use the method reference with the new keyword, which is called as Constructor reference.

List studentList = studentNames.stream().map(Student::new)
            .collect(Collectors.toList());

equivalent lambda expression

List studentList = studentNames.stream()
            .map(name -> new Student(name)).collect(Collectors.toList());

Happy Learning!!

Filed Under: Java Tagged With: Arbitrary object, Constructor Reference, Instance Method Reference, Java Method Reference, Method Reference, Static Method Reference

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·