I’ve current got a method which looks like:
public Map<Long, List<ReferralDetailsDTO>> getWaiting() { return referralDao.findAll() .stream() .map(ReferralDetailsDTO::new) .collect(Collectors.groupingBy(ReferralDetailsDTO::getLocationId, Collectors.toList())); } }
It returns me a Map of location IDs to ReferralDetailsDTO objects. However, I’d like to swap out the location ID for the LocationDTO object.
I’d have naively imagined something like this might work:
public Map<Long, List<ReferralDetailsDTO>> getWaiting() { return referralDao.findAll() .stream() .map(ReferralDetailsDTO::new) .collect(Collectors.groupingBy(locationDao.findById(ReferralDetailsDTO::getLocationId), Collectors.toList())); }
Obviously, I’m here because it doesn’t – Java complains the findById method is expecting a Long value, not the method reference. Any suggestions for how I can neatly address this? Thanks in advance.
Answer
First of all, change the key type of the Map from Long to your relevant class (is it LocationDTO
or some other class?)
Second of all, use a lambda expression instead of method reference for the lookup :
public Map<LocationDTO, List<ReferralDetailsDTO>> getWaiting() { return referralDao.findAll() .stream() .map(ReferralDetailsDTO::new) .collect(Collectors.groupingBy(r -> locationDao.findById(r.getLocationId())); }