I have two simple class ImageEntity and ImageList
how to collect result list ImageEntity to ImageList ?
List<File> files = listFiles();
ImageList imageList = files.stream().map(file -> {
return new ImageEntity(
file.getName(),
file.lastModified(),
rootWebPath + "/" + file.getName());
}).collect(toCollection(???));
class
public class ImageEntity {
private String name;
private Long lastModified;
private String url;
...
}
and
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);
}
}
It's not an elegant solution
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));
It can be a solution through collectingAndThen ?
what else have any ideas?
3.1. The toList collector can be used for collecting all Stream elements into a List instance.
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.
Using List. stream() method: Java List interface provides stream() method which returns a sequential Stream with this collection as its source.
Since ImageList
can be constructed from a List<ImageEntity>
, you can use 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));
On a separate note, you don't have to use the curly braces in your lambda expression. You can use file -> new ImageEntity(file.getName(), file.lastModified(), rootWebPath + "/" + file.getName())
you can try below also
ImageList imgList = new ImageList (files.stream().
.map(file -> { return new ImageEntity(file.getName(), file.lastModified(), rootWebPath + "/" + file.getName()) })
.collect(Collectors.toList()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With