2015-06-14 13 views
3

我已經得到了當前看起來像一個方法:如何將這些流式Map鍵從Longs轉換爲Objects?

public Map<Long, List<ReferralDetailsDTO>> getWaiting() { 
     return referralDao.findAll() 
       .stream() 
       .map(ReferralDetailsDTO::new) 
       .collect(Collectors.groupingBy(ReferralDetailsDTO::getLocationId, Collectors.toList())); 
    } 
} 

它返回我的位置ID,以ReferralDetailsDTO對象的地圖。但是,我想換出LocationDTO對象的位置ID。

我會天真地想象這樣的事情可能工作:

public Map<Long, List<ReferralDetailsDTO>> getWaiting() { 
    return referralDao.findAll() 
      .stream() 
      .map(ReferralDetailsDTO::new) 
      .collect(Collectors.groupingBy(locationDao.findById(ReferralDetailsDTO::getLocationId), Collectors.toList())); 
} 

很顯然,我在這裏,因爲它沒有 - 的Java抱怨的findById方法需要一個長期價值,而不是方法參考。對於我如何整潔地解決這個問題有什麼建議?提前致謝。

+2

沒有必要調用'groupingBy(...,toList())'。 「groupingBy」方法的一個參數(您爲管道中的數據提供密鑰映射的方法)已經將同一個鍵的值放入List中。 –

回答

5

首先,地圖的主要類型更改從長到你的相關類(是LocationDTO或其他一些類?)所有的

其次,使用lambda表達式而不是方法引用了查找:

public Map<LocationDTO, List<ReferralDetailsDTO>> getWaiting() { 
    return referralDao.findAll() 
      .stream() 
      .map(ReferralDetailsDTO::new) 
      .collect(Collectors.groupingBy(r -> locationDao.findById(r.getLocationId())); 
} 
相關問題