Search code examples
javabuilder

How to populate a list using the builder pattern in Java


I have this class which has a builder:

public class FieldValidationResponse {

  private Integer status;

  private String message;

  private List<FieldValidationError> errors;
  
}

I can build a FieldValidationResponse with an individual FieldValidationError like this:

private FieldValidationResponse fieldValidationResponse(String responseMessage, String message) {
    return FieldValidationResponse.builder()
        .message(responseMessage)
        .status(400)
        .error(
            FieldValidationError.builder()
                .message(message)
                .build()
        )
        .build();
}

Or I could build a FieldValidationResponse with multiple FieldValidationError like this:

private FieldValidationResponse fieldValidationResponse2(String responseMessage, List<String> messages) {
    List<FieldValidationError> fieldValidationErrors = new ArrayList<>();
    for (String message : messages) {
        fieldValidationErrors.add(
            FieldValidationError.builder()
                .message(message)
                .build()
        );
    }

    return FieldValidationResponse.builder()
        .message(responseMessage)
        .status(400)
        .errors(fieldValidationErrors)
        .build();
}

I feel that the way I am populating that list of FieldValidationError in the second method using the builder is not the "most elegant" way, I was wondering if I could improve that second method to populate a list?


Solution

  • can be achieved using stream.

      private FieldValidationResponse fieldValidationResponse2(
          String responseMessage, List<String> messages) {
    
        return FieldValidationResponse.builder()
            .message(responseMessage)
            .status(400)
            .errors(messages.stream().map(this::buildError).collect(Collectors.toList()))
            .build();
      }
    
      private FieldValidationError buildError(String message) {
        return FieldValidationError.builder().message(message).build();
      }