有实体:
@SuperBuilder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private String name;
private Integer age;
}
我顺流而下,在建筑商的帮助下收集了我的学生名单:
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());
}
构建器的这种用法正确吗?
是的,这个用法是正确的。你没有违反我熟悉的任何规则和模式。此外,你可以做一些这样的重构:
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();
}