2017-08-18 72 views
1

比方說,我有以下對象:爲什麼在執行flatmap()調用時會出現編譯錯誤?

public class DaylyData { 

private Date date; 
private List<Integer> numersList; 

// standard getters/setters 

public Map<Integer, Date> getIntToDate() { 
    Map<Integer, Date> resultMap = new HashMap<>(); 
    for(Integer number : getNumersList()) { 
     resultMap.put(number, getDate()); 
    } 
    return resultMap; 
} 

現在,讓我們說我有DaylyData的列表:List<DaylyData> resultList

什麼將是以下的結果:

resultList.stream().flatMap(entity -> entity.getIntToDate()); 

如果我的這個結果分配給Stream<Map<Integer, Date>>,我越來越Type mismatch: cannot convert from Map<Integer,Date> to Stream<? extends Map<Integer,Date>>

在此先感謝。

回答

2

flatMap方法是map的一種特殊情況,並且用於平坦化嵌套StreamOptional和其它一元工具。

在你的情況下,你沒有提供返回Stream的函數,所以它不能用作參數flatMap

你的功能將正常工作與標準map(),雖然:

resultList.stream() 
    .map(entity -> entity.getIntToDate()); // no compilation errors 

你可以通過在Stream例如包裝的結果讓你的榜樣工作,但這種不會給你在上面的例子中帶來任何好處 - 它是有道理這樣做只爲教育目的:

resultList.stream() 
    .flatMap(entity -> Stream.of(entity.getIntToDate())); // no compilation error 

這是「每天」而不是「DAYLY」。

相關問題