这里没有魔法,但您可以流式传输列表,然后实现 map 函数以从域表示形式转换为 DTO 表示形式。
例如,给定一个带有id, firstName, lastName 的域对象和一个带有id, name 的DTO(其中name 是firstName 和lastName 的串联),下面的代码...
List<MyObject> domain = new ArrayList<>();
domain.add(new MyObject(1, "John", "Smith"));
domain.add(new MyObject(1, "Bob", "Bailey"));
// using the verbose statement of function (rahter than a lambda)
// to make it easier to see how the map function works
List<MyDto> asDto = domain.stream().map(new Function<MyObject, MyDto>() {
@Override
public MyDto apply(MyObject s) {
// a simple mapping from domain to dto
return new MyDto(s.getId(), s.getFirstName() + " " + s.getLastName());
}
}).collect(Collectors.toList());
System.out.println(asDto);
...打印出来:
[
MyDto{id=1, name='John Smith'},
MyDto{id=1, name='Bob Bailey'}
]
当然,在使用stream() 时,上面对匿名类的使用看起来有些不合适,所以这里是使用 lambda 表示的相同代码:
List<MyDto> asDto = domain.stream().map(
s -> new MyDto(s.getId(), s.getFirstName() + " " + s.getLastName())
).collect(Collectors.toList());