Creating Java 8 Supplier with Constructor Arguments

Java 8 introduced the Supplier interface which allows you to generate or supply values without taking any input. However, sometimes it is necessary to create a Supplier that requires constructor arguments. In this case, you can make use of the lambda expression and method reference features of Java 8 to create a Supplier with constructor arguments.

├Źndice
  1. Using Lambda Expression
  2. Using Method Reference

Using Lambda Expression

You can use a lambda expression to create a Supplier with constructor arguments. Here is an example:


Supplier<Person> supplier = () -> new Person("John", "Doe");
Person person = supplier.get();

In the above example, we are using a lambda expression to create a Supplier that returns a Person object with constructor arguments.

Using Method Reference

Another way to create a Supplier with constructor arguments is by using a method reference. Here is an example:


Supplier<Person> supplier = Person::new;
Person person = supplier.get();

In the above example, we are using a method reference to create a Supplier that returns a Person object with constructor arguments. The ::new syntax refers to the constructor of the Person class.

In conclusion, creating a Supplier with constructor arguments in Java 8 is possible using lambda expressions and method references. These features allow you to create more versatile and flexible code.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

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

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information