Search code examples
javajava-streamlombok

How to build an entity in a Java stream?


There is entity:

@SuperBuilder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    private String name;

    private Integer age;

}

I make my way down the stream and collect a list of my students with the help of a builder:

public List<Student> getStudent(InputStream students) {
 return new BufferedReader(new InputStreamReader(students)).lines()
        .map(String::trim)
        .filter(line -> line.startsWith("a"))
        .map(line ->
            Student.builder()
                .name(line.substring(0, line.indexOf("this name")))
                .age(line.substring(line.indexOf("name")))
                .build())
        .collect(Collectors.toList());

}

Would this use of the builder be correct?


Solution

  • Yes, this usage is correct. You don't break any of the rules and patterns familiar to me. Besides, you can do some refactors like that:

    public List<Student> getStudent(Inputstream students) {
     return new BufferedReader(new InputStreamReader(students)).lines()
            .map(String::trim)
            .filter(line -> line.startsWith("a"))
            .map(this::makeStudent)
            .collect(toList());
    
    }
    
    private Student makeStudent(final String source){
        return Student.builder()
                      .name(source.substring(0, source.indexOf("this name")))
                      .age(source.substring(source.indexOf("name")))
                      .build();
    }