我有兩個簡單的類ImageEntity和的ImageListJava的8個流API如何收集清單對象
如何收集結果列表ImageEntity到圖像列表?
List<File> files = listFiles();
ImageList imageList = files.stream().map(file -> {
return new ImageEntity(
file.getName(),
file.lastModified(),
rootWebPath + "/" + file.getName());
}).collect(toCollection(???));
類
public class ImageEntity {
private String name;
private Long lastModified;
private String url;
...
}
和
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);
}
}
這不是一個完美的解決方案
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));
它可以通過collectingAndThen的解決方案?
還有什麼想法?
好!非常優雅!非常感謝! – Atum