Java 8 stream api how to collect List to Object

Atum picture Atum · Apr 26, 2016 · Viewed 21.6k times · Source

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?

Answer

Misha picture Misha · Apr 26, 2016

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())