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.
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.
Leave a Reply
Related posts