Atu*_*tum 3 lambda collect java-8 java-stream collectors
我有两个简单的类ImageEntity和ImageList
如何将结果列表ImageEntity收集到ImageList?
List<File> files = listFiles();
ImageList imageList = files.stream().map(file -> {
return new ImageEntity(
file.getName(),
file.lastModified(),
rootWebPath + "/" + file.getName());
}).collect(toCollection(???));
Run Code Online (Sandbox Code Playgroud)
类
public class ImageEntity {
private String name;
private Long lastModified;
private String url;
...
}
Run Code Online (Sandbox Code Playgroud)
和
public class ImageList {
private List<ImageEntity> list;
public ImageList() {
list = new ArrayList<>();
}
public ImageList(List<ImageEntity> list) {
this.list = list;
}
public boolean add(ImageEntity entity) {
return list.add(entity);
}
public void addAll(List<ImageEntity> list) {
list.addAll(entity);
}
}
Run Code Online (Sandbox Code Playgroud)
这不是一个优雅的解决方案
ImageList imgList = files.stream().
.map(file -> { return new ImageEntity(file.getName(), file.lastModified(), rootWebPath + "/" + file.getName()) })
.collect(ImageList::new, (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2));
Run Code Online (Sandbox Code Playgroud)
它可以通过收集和解决方案来解决?
还有什么想法?
既然ImageList可以用a构建List<ImageEntity>,你可以使用Collectors.collectingAndThen:
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.collectingAndThen;
ImageList imgList = files.stream()
.map(...)
.collect(collectingAndThen(toList(), ImageList::new));
Run Code Online (Sandbox Code Playgroud)
另外,您不必在lambda表达式中使用花括号.您可以使用file -> new ImageEntity(file.getName(), file.lastModified(), rootWebPath + "/" + file.getName())
| 归档时间: |
|
| 查看次数: |
14744 次 |
| 最近记录: |