GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Private Policy
  • Contact
  • Java
  • Java Core
  • Java Lambda Expression
  • Java Fundamentals
  • Java Stream
  • Java Tools
  • Java XML
  • Jakarta EE
  • CDI
  • JSON Binding
  • JSON Processing
  • MVC

This view

  • Original page
  • New address

GeezerVison is showing huongdanjava.com — Constructor reference in Java - Huong Dan Java

Khanh Nguyen

I love Java and everything related to Java.

Follow

Share this post

Tags

  • Java Lambda Expression
Views: 1,066

I have introduced the method reference in the previous tutorial, in this tutorial, I introduce you another new concept: constructor reference. Like the method reference, the constructor reference is used to abbreviate the Lambda Expression expression. How is it in details?

Suppose you are working with a Lambda Expression like this:

Java
1
(args) -> new ClassName(args)

In this expression Lambda Expression, the body part we have only a code for initializing a new object with the constructor having or not having argument parameters.

To be concise, we can use the constructor reference as follows:

Java
1
ClassName::new

For the example of this constructor reference, I will use some of the interfaces in the java.util.function package.

With the constructor without parameters, we will use the Supplier interface with the Lambda Expression expression as follows:

Java
1
Supplier<List<String>> s = () -> new ArrayList<>();

Rewrite with the constructor reference:

Java
1
Supplier<List<String>> s = ArrayList::new;

Given a constructor with a parameter, we will use the Function interface with the Lambda Expression expression as follows:

Java
1
Function<String, Integer> f = s -> new Integer(s);

Rewrite with the constructor reference:

Java
1
Function<String, Integer> f = Integer::new;

You might also like...

  • What is a Database Transaction? ACID, JDBC & Isolation Levels

    What is a Database Transaction? ACID, JDBC & Isolation Levels

  • What is JDBC? JDBC Architecture, Driver, Connection, Statement & PreparedStatement | Java

    What is JDBC? JDBC Architecture, Driver, Connection, Statement & PreparedStatement | Java

  • Java Primitive Data Types Part 2 | float, double, boolean

    Java Primitive Data Types Part 2 | float, double, boolean

  • Java Primitive Data Types Part 1 | byte, short, int, long, char & Type Conversion

    Java Primitive Data Types Part 1 | byte, short, int, long, char & Type Conversion

Previous Post: Method reference in Java
Next Post: Delete directory in Java

Add Comment Cancel reply

You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.