avatarVinotech

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

9356

Abstract

js-params">(String[] args)</span> { <span class="hljs-comment">// Create an instance of the class</span> <span class="hljs-type">InstanceMethodReferenceExample</span> <span class="hljs-variable">example</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">InstanceMethodReferenceExample</span>();

    <span class="hljs-comment">// Create a list of strings</span>
    List&lt;String&gt; messages = Arrays.asList(<span class="hljs-string">"Hello"</span>, <span class="hljs-string">"World"</span>, <span class="hljs-string">"Java"</span>, <span class="hljs-string">"Method Reference"</span>);
    
    <span class="hljs-comment">// Using lambda expression to print each message</span>
    messages.forEach(msg -&gt; example.printMessage(msg));
    
    <span class="hljs-comment">// Using method reference to an instance method of a particular object</span>
    messages.forEach(example::printMessage);
}

}</pre></div><p id="3086"><b>3. A method reference to an instance method of an existing object </b>A <b>reference to an instance method of an arbitrary object of a particular type</b> in Java 8 refers to cases where you call an instance method on an object of a specific type, but the object is not explicitly defined when the method reference is made.</p><p id="7980">This is commonly used in stream operations, where you can apply a method on elements of a collection. The syntax for this method reference is <code>ClassName::methodName</code>.</p><p id="309e"><b>Example 1 :</b></p><div id="c7ea"><pre><span class="hljs-keyword">import</span> java.util.Arrays; <span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">InstanceMethodReferenceExample</span> {

<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
    <span class="hljs-comment">// Create a list of strings</span>
    List&lt;String&gt; messages = Arrays.asList(<span class="hljs-string">"hello"</span>, <span class="hljs-string">"world"</span>, <span class="hljs-string">"java"</span>, <span class="hljs-string">"method reference"</span>);
    
    <span class="hljs-comment">// Using lambda expression to convert each string to uppercase</span>
    messages.stream()
            .map(s -&gt; s.toUpperCase()) <span class="hljs-comment">// lambda version</span>
            .forEach(System.out::println);
    
    <span class="hljs-comment">// Using method reference to an instance method of an arbitrary object</span>
    messages.stream()
            .map(String::toUpperCase)  <span class="hljs-comment">// method reference version</span>
            .forEach(System.out::println);
}

}

<span class="hljs-comment">// OUTPUT </span> HELLO WORLD JAVA METHOD REFERENCE</pre></div><h2 id="a4bc">Explanation:</h2><ul><li><code>String::toUpperCase</code> is a reference to the <code>toUpperCase</code> instance method of the <code>String</code> class.</li><li>Here, we are not specifying which particular <code>String</code> object to use when defining the method reference. Instead, the method reference will be applied to each element in the stream (which are <code>String</code> objects).</li><li>The method reference <code>String::toUpperCase</code> applies the <code>toUpperCase</code> method on each <code>String</code> in the <code>messages</code> list during the stream operation.</li></ul><p id="3afc"><b>Example 2 : Reference to an Instance Method of an Arbitrary Object of a Particular Type</b></p><div id="fb4f"><pre><span class="hljs-keyword">import</span> java.util.Arrays; <span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Person</span> { <span class="hljs-keyword">private</span> String name; <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> age;

<span class="hljs-keyword">public</span> <span class="hljs-title function_">Person</span><span class="hljs-params">(String name, <span class="hljs-type">int</span> age)</span> {
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.age = age;
}

<span class="hljs-keyword">public</span> String <span class="hljs-title function_">getName</span><span class="hljs-params">()</span> {
    <span class="hljs-keyword">return</span> name;
}

<span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">getAge</span><span class="hljs-params">()</span> {
    <span class="hljs-keyword">return</span> age;
}

}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">InstanceMethodReferenceExample</span> { <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> { <span class="hljs-comment">// Creating a list of Person objects</span> List<Person> people = Arrays.asList( <span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">30</span>), <span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"Bob"</span>, <span class="hljs-number">25</span>), <span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"Charlie"</span>, <span class="hljs-number">35</span>) );

    <span class="hljs-comment">// Using lambda expression to get names</span>
    people.stream()
          .map(person -&gt; person.getName())  <span class="hljs-comment">// lambda version</span>
          .forEach(System.out::println);

    <span class="hljs-comment">// Using method reference to an instance method of an arbitrary object</span>
    people.stream()
          .map(Person::getName)  <span class="hljs-comment">// method reference version</span>
          .forEach(System.out::println);
}

}

<span class="hljs-comment">// OUTPUT</span> Alice Bob Charlie</pre></div><h2 id="6416">Explanation:</h2><ul><li><code>Person::getName</code> is a reference to the <code>getName</code> instance method of the <code>Person</code> class.</li><li>The method reference applies the <code>getName()</code> method on each <code>Person</code> object in the list, retrieving the name for each person.</li><li>This is more concise than using the lambda expression <code>person -> person.getName()</code>.</li></ul><p id="0afa"><b>4. Reference to a Constructor</b></p><p id="baa8">In Java 8, <b>constructor references</b> allow you to refer to constructors using the <code>ClassName::new</code> syntax. Constructor references are particularly useful when working with functional interfaces like <code>Supplier</code>, <code>Function</code>, and <code>BiFunction</code>. They provide a concise way to create new objects.</p><h2 id="ba8e">Example 1: Constructor Reference with No Arguments</h2><p id="de6a">In this example, we’ll create a simple class <code>Person</code> with a no-argument constructor and use a constructor reference to create a new <code>Person</code> object.</p><div id="58a8"><pre><span class="hljs-keyword">import</span> java.util.function.Supplier;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Person</span> { <span class="hljs-keyword">private</span> String name;

<span class="hljs-keyword">public</span> <span class="hljs-title function_">Person</span><span class="hljs-params">()</span> {
    <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"Unknown"</span>;
}

<span class="hljs-keyword">public</span> String <span class="hljs-title function_">getName</span><span class="hljs-params">()</span> {
    <span class="hljs-keyword">return</span> name;
}

}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ConstructorReferenceExample1</span> { <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> { <span class="hljs-comment">// Using lambda expression to create a new Person</span> Supplier<Person> personSupplierLambda = () -> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(); <span class="hljs-type">Person</span> <span class="hljs-variable">person1</span> <span class="hljs-operator">=</span> personSupplierLambda.get(); System.out.println(<span class="hljs-string">"Person 1 Name: "</span> + person1.getName()); <span class="hljs-comment">// Output: Person 1 Name: Unknown</span>

    <span class="hljs-com

Options

ment">// Using constructor reference to create a new Person</span> Supplier<Person> personSupplierRef = Person::<span class="hljs-keyword">new</span>; <span class="hljs-type">Person</span> <span class="hljs-variable">person2</span> <span class="hljs-operator">=</span> personSupplierRef.get(); System.out.println(<span class="hljs-string">"Person 2 Name: "</span> + person2.getName()); <span class="hljs-comment">// Output: Person 2 Name: Unknown</span> } }

<span class="hljs-comment">//Output</span> Person <span class="hljs-number">1</span> Name: Unknown Person <span class="hljs-number">2</span> Name: Unknown</pre></div><h2 id="97c9">Explanation:</h2><ul><li><code>Supplier<Person></code> is a functional interface that supplies a <code>Person</code> object.</li><li>The lambda expression <code>() -> new Person()</code> creates a new <code>Person</code> using the no-argument constructor.</li><li>The constructor reference <code>Person::new</code> is a concise way to reference the <code>Person</code> constructor without arguments.</li><li>Both the lambda and constructor reference versions create a <code>Person</code> with the default name <code>"Unknown"</code>.</li></ul><h2 id="f972">Example 2: Constructor Reference with Arguments</h2><p id="a9a5">In this example, we’ll modify the <code>Person</code> class to include a constructor that accepts arguments and use a constructor reference with the <code>Function</code> interface to create new <code>Person</code> objects.</p><div id="742d"><pre><span class="hljs-keyword">import</span> java.<span class="hljs-property">util</span>.<span class="hljs-property">function</span>.<span class="hljs-property">Function</span>;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Person</span> { <span class="hljs-keyword">private</span> <span class="hljs-title class_">String</span> name; <span class="hljs-keyword">private</span> int age;

<span class="hljs-keyword">public</span> <span class="hljs-title class_">Person</span>(<span class="hljs-title class_">String</span> name, int age) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">name</span> = name;
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">age</span> = age;
}

<span class="hljs-keyword">public</span> <span class="hljs-title class_">String</span> <span class="hljs-title function_">getName</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">return</span> name;
}

<span class="hljs-keyword">public</span> int <span class="hljs-title function_">getAge</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">return</span> age;
}

}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ConstructorReferenceExample2</span> { <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">main</span>(<span class="hljs-params"><span class="hljs-built_in">String</span>[] args</span>) { <span class="hljs-comment">// Using lambda expression to create a new Person with name and age</span> <span class="hljs-title class_">Function</span><<span class="hljs-title class_">String</span>, <span class="hljs-title class_">Person</span>> personFunctionLambda = (name) -> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(name, <span class="hljs-number">25</span>); <span class="hljs-title class_">Person</span> person1 = personFunctionLambda.<span class="hljs-title function_">apply</span>(<span class="hljs-string">"Alice"</span>); <span class="hljs-title class_">System</span>.<span class="hljs-property">out</span>.<span class="hljs-title function_">println</span>(<span class="hljs-string">"Person 1: "</span> + person1.<span class="hljs-title function_">getName</span>() + <span class="hljs-string">", Age: "</span> + person1.<span class="hljs-title function_">getAge</span>()); <span class="hljs-comment">// Output: Alice, Age: 25</span>

    <span class="hljs-comment">// Using constructor reference to create a new Person</span>
    <span class="hljs-title class_">Function</span>&lt;<span class="hljs-title class_">String</span>, <span class="hljs-title class_">Person</span>&gt; personFunctionRef = name -&gt; <span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(name, <span class="hljs-number">25</span>);
    <span class="hljs-title class_">Person</span> person2 = personFunctionRef.<span class="hljs-title function_">apply</span>(<span class="hljs-string">"Bob"</span>);
    <span class="hljs-title class_">System</span>.<span class="hljs-property">out</span>.<span class="hljs-title function_">println</span>(<span class="hljs-string">"Person 2: "</span> + person2.<span class="hljs-title function_">getName</span>() + <span class="hljs-string">", Age: "</span> + person2.<span class="hljs-title function_">getAge</span>()); <span class="hljs-comment">// Output: Bob, Age: 25</span>
}

}

<span class="hljs-comment">//Output</span> <span class="hljs-title class_">Person</span> <span class="hljs-number">1</span>: <span class="hljs-title class_">Alice</span>, <span class="hljs-title class_">Age</span>: <span class="hljs-number">25</span> <span class="hljs-title class_">Person</span> <span class="hljs-number">2</span>: <span class="hljs-title class_">Bob</span>, <span class="hljs-title class_">Age</span>: <span class="hljs-number">25</span></pre></div><h2 id="df5b">Explanation:</h2><ul><li><code>Function<String, Person></code> is a functional interface that takes a <code>String</code> (name) and returns a <code>Person</code> object.</li><li>The lambda expression <code>(name) -> new Person(name, 25)</code> creates a new <code>Person</code> with a specified name and age <code>25</code>.</li><li>The constructor reference <code>Person::new</code> (for an overloaded constructor with parameters) is a concise way to create a new <code>Person</code> object with the provided name, but in this case, the constructor requires two arguments (<code>name</code> and <code>age</code>), so we need to specify age directly in the lambda.</li></ul><blockquote id="a6a3"><p><i>👏<b> If you found my articles useful, please consider giving it claps and sharing it with your friends and colleagues.</b></i></p></blockquote><p id="6a48"><b>To read other topics</b></p><ul><li><a href="https://readmedium.com/comprehensive-guide-to-java-concurrency-executorservice-thread-pools-future-runnable-and-185a11bcdf46"><b>ExecutorService, Thread Pools, Future Interface, Runnable, and Callable</b></a></li><li><a href="https://readmedium.com/spring-boot-circuit-breaker-example-with-resilience4j-step-by-step-guide-e4c6f82711e5"><b>Spring Boot Circuit Breaker Example with Resilience4j: Step-by-Step Guide</b></a></li><li><a href="https://readmedium.com/spring-boot-retry-pattern-example-with-resilience4j-step-by-step-guide-91f98b382b35"><b>Spring Boot Retry Pattern Example with Resilience4j: Step-by-Step Guide</b></a></li><li><a href="https://readmedium.com/transactional-annotation-in-spring-data-jpa-9f803d341289"><b>Mastering Transaction Propagation and Isolation in Spring Boot</b></a></li><li><a href="https://readmedium.com/using-hibernate-formula-in-spring-boot-to-compute-derived-fields-dynamically-21006573a82c"><b>@Formula Annotation in Spring Boot</b></a></li><li><a href="https://readmedium.com/understanding-logging-in-spring-boot-a-complete-overview-with-example-32b5cdfb16b8"><b>Understanding Logging in Spring Boot: A Complete Overview with Example</b></a></li><li><a href="https://readmedium.com/understanding-hash-collisions-in-javas-hashmap-24ed1856e71d"><b>Understanding Hash Collisions in Java’s HashMap</b></a></li><li><a href="https://readmedium.com/exploring-java-collections-a-guide-to-lists-sets-queues-and-maps-a1c06a9f674c"><b>Exploring Java Collections: A Guide to Lists, Sets, Queues, and Maps</b></a></li><li><a href="https://readmedium.com/using-the-temporal-annotation-in-hibernate-and-spring-boot-f8b46679af1d"><b>Using the @Temporal Annotation in Hibernate and Spring Boot</b></a></li><li><a href="https://readmedium.com/understanding-cors-and-csrf-in-spring-boot-7a2d92259592"><b>Understanding CORS and CSRF in Spring Boot</b></a></li><li><a href="https://readmedium.com/complete-crud-example-in-spring-boot-with-dto-validation-and-common-api-response-using-mysql-222679cbe4d5"><b>Complete CRUD Example in Spring Boot with DTO Validation, and Common API Response using MySQL</b></a></li><li><a href="https://readmedium.com/guide-to-spring-boot-validation-annotations-07b95963eac0"><b>Guide to Spring Boot Validation Annotations</b></a></li><li><a href="https://readmedium.com/mastering-git-and-github-integration-in-intellij-idea-a-complete-guide-to-version-control-7cf68cd7951a"><b>Mastering Git and GitHub Integration in IntelliJ IDEA</b></a></li><li><a href="https://readmedium.com/spring-boot-profiles-3df0345505f3"><b>Spring Boot Profiles</b></a></li><li><a href="https://readmedium.com/design-pattern-in-java-14289cc56f5b"><b>Design Pattern in java</b></a></li></ul></article></body>

Method References in Java 8

  1. Method references are shorthand notations for lambda expressions that directly call a method or constructors using the :: operator.
  2. Method references provide a way to refer to a method without executing it. Instead of creating a lambda expression to perform a specific operation, developers can reference an existing method to perform the same operation.
  3. Method references provide a concise syntax for invoking a method, and they can be used in place of lambda expressions in certain cases.

Difference Between Lambda Expression and Method Reference

  • Use lambda expressions when you need to implement behavior that isn’t directly tied to a method.
  • Use method references when you can directly refer to existing methods for a clearer and more concise syntax.
  • Lambda Expression: More flexible; can include custom logic.
  • Method Reference: Less flexible; limited to existing methods.

In Java, there are four types of method references:

  1. A method reference to a static method
Syntax: ClassName::staticMethodName
Example: Math::max

2. A method reference to an instance method of an object of a particular type

Syntax: instance::methodName
Example: System.out::println

3. A method reference to an instance method of an existing object

Syntax: ClassName::instanceMethodName
Example: String::toLowerCase

4. A method reference to a constructor

Syntax: ClassName::new
Example: ArrayList::new

For each type of Method reference, I have discussed two examples. After finishing, you will be able to understand method reference deeply. Please giving it claps👏 if this article is useful.

Functional interface knowledge is required to read this article. Please refer my article for functional interface.

1. Reference to a Static Method

Example 1: Basic usage of method reference to a static method

import java.util.Arrays;
import java.util.List;

public class StaticMethodReferenceExample {
    // Static method
    public static void printMessage(String message) {
        System.out.println(message);
    }

    public static void main(String[] args) {
        List<String> messages = Arrays.asList("Hello", "World", "Java 8");

        // Using method reference to a static method
        messages.forEach(StaticMethodReferenceExample::printMessage);
    }
}

Example 2: Method reference with built-in static method (e.g., Integer::parseInt)

import java.util.function.Function;
import java.util.Arrays;
import java.util.List;

public class StaticMethodReferenceWithBuiltInMethod {
    public static void main(String[] args) {
        List<String> numbers = Arrays.asList("1", "2", "3", "4");

        // Using method reference for built-in static method Integer::parseInt
        Function<String, Integer> parseIntFunction = Integer::parseInt;

        numbers.stream()
               .map(parseIntFunction) // Converts each string to an integer
               .forEach(System.out::println); // Prints each integer
    }
}

2. Reference to an Instance Method Example 1 :

import java.util.function.Function;

public class MethodReferenceExample {

    public String convertToUpperCase(String input) {
        return input.toUpperCase();
    }

    public static void main(String[] args) {
        // Creating an instance of the class
        MethodReferenceExample example = new MethodReferenceExample();
        
        // Using lambda expression
        Function<String, String> lambdaFunction = s -> example.convertToUpperCase(s);
        
        // Using method reference
        Function<String, String> methodRefFunction = example::convertToUpperCase;
        
        // Test the method reference
        String result = methodRefFunction.apply("hello");
        System.out.println(result); // Output: HELLO
    }
}
  • example::convertToUpperCase is the method reference to the instance method convertToUpperCase of the example object.
  • This is more concise than using a lambda like s -> example.convertToUpperCase(s).

Example 2 : Reference to an Instance Method in a Collection

import java.util.Arrays;
import java.util.List;

public class InstanceMethodReferenceExample {

    public void printMessage(String message) {
        System.out.println(message);
    }

    public static void main(String[] args) {
        // Create an instance of the class
        InstanceMethodReferenceExample example = new InstanceMethodReferenceExample();
        
        // Create a list of strings
        List<String> messages = Arrays.asList("Hello", "World", "Java", "Method Reference");
        
        // Using lambda expression to print each message
        messages.forEach(msg -> example.printMessage(msg));
        
        // Using method reference to an instance method of a particular object
        messages.forEach(example::printMessage);
    }
}

3. A method reference to an instance method of an existing object A reference to an instance method of an arbitrary object of a particular type in Java 8 refers to cases where you call an instance method on an object of a specific type, but the object is not explicitly defined when the method reference is made.

This is commonly used in stream operations, where you can apply a method on elements of a collection. The syntax for this method reference is ClassName::methodName.

Example 1 :

import java.util.Arrays;
import java.util.List;

public class InstanceMethodReferenceExample {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> messages = Arrays.asList("hello", "world", "java", "method reference");
        
        // Using lambda expression to convert each string to uppercase
        messages.stream()
                .map(s -> s.toUpperCase()) // lambda version
                .forEach(System.out::println);
        
        // Using method reference to an instance method of an arbitrary object
        messages.stream()
                .map(String::toUpperCase)  // method reference version
                .forEach(System.out::println);
    }
}

// OUTPUT 
HELLO
WORLD
JAVA
METHOD REFERENCE

Explanation:

  • String::toUpperCase is a reference to the toUpperCase instance method of the String class.
  • Here, we are not specifying which particular String object to use when defining the method reference. Instead, the method reference will be applied to each element in the stream (which are String objects).
  • The method reference String::toUpperCase applies the toUpperCase method on each String in the messages list during the stream operation.

Example 2 : Reference to an Instance Method of an Arbitrary Object of a Particular Type

import java.util.Arrays;
import java.util.List;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class InstanceMethodReferenceExample {
    public static void main(String[] args) {
        // Creating a list of Person objects
        List<Person> people = Arrays.asList(
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("Charlie", 35)
        );
        
        // Using lambda expression to get names
        people.stream()
              .map(person -> person.getName())  // lambda version
              .forEach(System.out::println);

        // Using method reference to an instance method of an arbitrary object
        people.stream()
              .map(Person::getName)  // method reference version
              .forEach(System.out::println);
    }
}

// OUTPUT
Alice
Bob
Charlie

Explanation:

  • Person::getName is a reference to the getName instance method of the Person class.
  • The method reference applies the getName() method on each Person object in the list, retrieving the name for each person.
  • This is more concise than using the lambda expression person -> person.getName().

4. Reference to a Constructor

In Java 8, constructor references allow you to refer to constructors using the ClassName::new syntax. Constructor references are particularly useful when working with functional interfaces like Supplier, Function, and BiFunction. They provide a concise way to create new objects.

Example 1: Constructor Reference with No Arguments

In this example, we’ll create a simple class Person with a no-argument constructor and use a constructor reference to create a new Person object.

import java.util.function.Supplier;

class Person {
    private String name;

    public Person() {
        this.name = "Unknown";
    }

    public String getName() {
        return name;
    }
}

public class ConstructorReferenceExample1 {
    public static void main(String[] args) {
        // Using lambda expression to create a new Person
        Supplier<Person> personSupplierLambda = () -> new Person();
        Person person1 = personSupplierLambda.get();
        System.out.println("Person 1 Name: " + person1.getName());  // Output: Person 1 Name: Unknown

        // Using constructor reference to create a new Person
        Supplier<Person> personSupplierRef = Person::new;
        Person person2 = personSupplierRef.get();
        System.out.println("Person 2 Name: " + person2.getName());  // Output: Person 2 Name: Unknown
    }
}

//Output
Person 1 Name: Unknown
Person 2 Name: Unknown

Explanation:

  • Supplier<Person> is a functional interface that supplies a Person object.
  • The lambda expression () -> new Person() creates a new Person using the no-argument constructor.
  • The constructor reference Person::new is a concise way to reference the Person constructor without arguments.
  • Both the lambda and constructor reference versions create a Person with the default name "Unknown".

Example 2: Constructor Reference with Arguments

In this example, we’ll modify the Person class to include a constructor that accepts arguments and use a constructor reference with the Function interface to create new Person objects.

import java.util.function.Function;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class ConstructorReferenceExample2 {
    public static void main(String[] args) {
        // Using lambda expression to create a new Person with name and age
        Function<String, Person> personFunctionLambda = (name) -> new Person(name, 25);
        Person person1 = personFunctionLambda.apply("Alice");
        System.out.println("Person 1: " + person1.getName() + ", Age: " + person1.getAge()); // Output: Alice, Age: 25

        // Using constructor reference to create a new Person
        Function<String, Person> personFunctionRef = name -> new Person(name, 25);
        Person person2 = personFunctionRef.apply("Bob");
        System.out.println("Person 2: " + person2.getName() + ", Age: " + person2.getAge()); // Output: Bob, Age: 25
    }
}

//Output
Person 1: Alice, Age: 25
Person 2: Bob, Age: 25

Explanation:

  • Function<String, Person> is a functional interface that takes a String (name) and returns a Person object.
  • The lambda expression (name) -> new Person(name, 25) creates a new Person with a specified name and age 25.
  • The constructor reference Person::new (for an overloaded constructor with parameters) is a concise way to create a new Person object with the provided name, but in this case, the constructor requires two arguments (name and age), so we need to specify age directly in the lambda.

👏 If you found my articles useful, please consider giving it claps and sharing it with your friends and colleagues.

To read other topics

Method References
Java8
Java 8 Feature
Java8 Tutorial
Method Reference Operator
Recommended from ReadMedium