Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call constructor with arguments in a lambda expression [duplicate]

Tags:

java

lambda

I have Employee class:

public class Employee {

    private Long id;
    private String name;
    private String externalId;

    public Employee(Long id, String name, String externalId) {
        this.id = id;
        this.name = name;
        this.externalId = externalId;
    }

    //getters, setter
}

And employee service which returns an employee (NULL is possible).

private void performEmployeeProcessing() {
    Long employeeId = 2L;
    Object o = Optional.ofNullable(employeeService.getById(employeeId))
        .orElseGet(Employee::new, 1L, "", "");

    System.out.println(o);
}

It says compilation error

Employee::new, 1L, "", ""
Cannot resolve constructor.

like image 744
Yan Khonski Avatar asked Jan 16 '26 22:01

Yan Khonski


1 Answers

Use a Supplier:

.orElseGet(() -> new Employee( 1L, "", ""));

FYI, an Employee instance will only be created when it's actually needed.


If your constructor had no args, you could have used a method reference Employee::new. You could still use a method reference if you create a factory method:

class Employee {
    // rest of class
    public static Employee createDummy() {
        return new Employee( 1L, "", "");
    }
}

then you could:

.orElseGet(Employee::createDummy);

The factory method could actually be in any class as you like.

like image 149
Bohemian Avatar answered Jan 19 '26 19:01

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!