我经常看到类似以下的代码库
public class SomeService(){
public List<someObject> getSomePs{
return someObjectRepo.getAll()
.stream()
.filter(it -> it.name.startsWith("P"))
.collect(Collectors.toList());
}
}
public class SomeController(){
@Inject
SomeService someService;
public List<someObjectDto> getSome{
List<someObj> list = someService.getSomePs();
return list.stream()
.map(SomeConverter::convert)
.collect(Collectors.toList());
}
}
服务返回流而不是收集流并创建无用的中间对象是一种不好的做法吗?
public class SomeService(){
public Stream<SomeObj> getSomePs{
return someObjectRepo.getAll()
.stream()
.filter(it -> it.name.startsWith("P"));
}
}
public class SomeController(){
@Inject
SomeService someService;
public List<someObjectDto> getSome{
return someService.getSomePs()
.map(SomeConverter::convert)
.collect(Collectors.toList());
}
}
从理论上讲,这不是更少的代码,而是更具可读性吗?由于没有中间变量,因此占用空间也较小?还是有一些我没有看到的例外?还是有任何不合需要的强烈理由?