2017-04-23 70 views
0

我正在嘗試編寫一段代碼,它執行以下操作(pseudocodish),但是使用流。我試圖弄清楚,但我似乎無法正確地映射它。我可能錯過了一些我忽略了一些東西的知識。任何人都有能幫助我的知識嗎?Java流列表<X>到地圖<X, List<Y>>

在此先感謝! :-)

Map<X, List<Y>> result= ...; 

List<X> allX = getAllNeededX(); 
for(X x : allX) { 
    List<Y> matchingY = getMatchingY(x.id); 
    SortListOfYByProperty 
    result.put(x, sortedY) 
} 
+0

您正在努力的部分是? –

+0

你的地圖應該代表什麼? –

+1

到目前爲止你試過了什麼? – Flown

回答

2

以下是一些選項。

public static void main(String[] args) { 

    Map<X, List<Y>> results = new HashMap<>(); 
    List<X> allX = getAllX(); 

    //simple way to just replace old for loop with forEach 
    allX.stream().forEach(x -> { 
     List<Y> matchingY = getMatchingY(x.id); 
     sortListY(matchingY); 
     results.put(x, matchingY); 
    }); 

    //a little bit fancier, assumes sortListY return List<Y> 
    allX.stream() 
      .map((X x) -> new AbstractMap.SimpleEntry<>(x, sortListY(getMatchingY(x.id)))) 
      .forEach(e -> results.put(e.getKey(), e.getValue())); 

    //more fancy, assumes sortListY return List<Y> 
    Map<X, List<Y>> results2 = allX.stream() 
      .map((X x) -> new AbstractMap.SimpleEntry<>(x, sortListY(getMatchingY(x.id)))) 
      .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); 

    //most fancy, assumes sortListY return List<Y> 
    Map<X, List<Y>> results3 = allX.stream() 
      .collect(Collectors.toMap(Function.identity(), x -> sortListY(getMatchingY(x.id)))); 


    //most fancy part 2, assumes sortListY return List<Y> 
    Map<X, List<Y>> results4 = allX.stream() 
      .collect(Collectors.toMap(x -> x, x -> sortListY(getMatchingY(x.id)))); 

} 
+1

你應該在'collect()'內執行'sortListY()',這將避免中間映射到條目。 –

+1

@DidierL好主意,讓我試試,謝謝 –

1

Didier的鏈接幫了我很多。

我可以創建X的第一個列表,併爲Y的排序列表創建一個單獨的流,但是我無法將它全部組合在一起。

隨着德羅巴的鏈接我來到了以下內容,這使我的單元測試成功:

return getAllX().stream().collect(toMap(x -> x, x -> getSortedAndMatchingY(x.id))); 

通過從這個來源的鏈接移動整理到一個單獨的方法,上面的回答提出並使用一些輸入記住,它似乎工作。感謝您的輸入:-)

相關問題