Search code examples
javajava-8lombokbuilder

Create List using Builder Pattern in Java


I am having a class that takes a string and a List object . I am able to create a List object separately using builder and pass it to another builder to create an object . But it does not looks like a nice way . Is their any way to merge these 2 builders in one builder.

@Data
@Builder
public class CustomerRequest{
private String cutspec;
private List<Customer> listOfcustomer;
}

Current Implementation

Customer customer = Customer.builder().conditionType("valueCondition").key("customerNo")
            .operator("=").value(customerId).build();
    
    List<Customer> listOfcustomer = new ArrayList<>();
    listOfcustomer.add(customer);

    return CustomerRequest.builder().name("John").simplecustomer(listOfcustomer).build();

Solution

  • Using Java 9's List.of()-Method you can do:

    return CustomerRequest.builder()
        .name("John")
        .simplecustomer(List.of(
            Customer.builder().conditionType("valueCondition").key("customerNo")
                .operator("=").value(customerId).build()
        ))
        .build();
    

    Just be aware that the resulting List is immutable.