2016-04-26 89 views
2

我有兩個簡單的類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的解決方案?

還有什麼想法?

回答

2

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

+0

好!非常優雅!非常感謝! – Atum

1

你可以試試下面也

ImageList imgList = new ImageList (files.stream(). 
    .map(file -> { return new ImageEntity(file.getName(), file.lastModified(), rootWebPath + "/" + file.getName()) }) 
    .collect(Collectors.toList())); 
+0

這真的很奇怪,Collectors.toList()如何返回Object而不是對象列表。你能解釋一下嗎? – Mitchapp

+0

它是我的錯誤,我認爲'ImageList'爲'List '。我們應該有'.collect(converttoImageList());' –

1

的collectingAndThen方法有創建列表,然後複製它的缺點。

如果你想的東西比你最初collect例如更具可重用性,而且,像你的榜樣,並沒有結束在collectingAndThen收集做一個額外的副本,你可以採取collect的三個參數,並作出類似Collectors.toList()功能直接收集到你的ImageList,像這樣:

public static Collector<ImageEntity,?,ImageList> toImageList() { 
    return Collector.of(ImageList::new, (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2)); 
} 

然後,您可以使用這樣的:

ImageList imgList = files.stream(). 
    .map(file -> new ImageEntity(file.getName(), file.lastModified(), rootWebPath + "/" + file.getName())) 
    .collect(toImageList());