我有两个简单的类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(???));
类
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));
可以通过collectAndThen解决方案吗?
还有什么想法?
最佳答案
由于可以从ImageList
构造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));
另外,您不必在lambda表达式中使用花括号。您可以使用
file -> new ImageEntity(file.getName(), file.lastModified(), rootWebPath + "/" + file.getName())
关于lambda - Java 8 Stream API如何收集列表到对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36855733/