2017-04-23 9 views
0

나는 다음과 같은 (pseudocodish) 코드를 작성하려고하지만 스트림이있다. 알아 내기 위해 노력하고 있지만 제대로 매핑되지 않은 것 같습니다. 아마 나는 뭔가를 간과하고 있다는 지식을 잃어 버렸을 것입니다. 아무도 나를 도울 수있는 지식이 있습니까?자바 스트림리스트 <X> to map <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

디디에 링크가 도움이되었습니다.

나는 X의 첫 번째 목록과 Y의 정렬 된 목록을위한 별도의 스트림을 만들 수 있었지만 모두 결합 할 수는 없었다.

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

을이 제공된 링크에서 위의 대답은 제안으로 별도의 방법으로 정렬 이동 및 일부 입력을 사용하여 : 디디에의 링크

나는 성공을 내 유닛 테스트를 만든 다음, 온 마음에 그것은 작동하는 것 같습니다. 입력 해 주셔서 감사합니다 :-)

관련 문제