我目前有一个看起来像这样的方法:
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 方法需要一个 Long 值,而不是方法引用。关于如何巧妙地解决这个问题有什么建议吗?提前致谢。
最佳答案
首先,将 Map 的键类型从 Long 更改为您的相关类(是 LocationDTO
还是其他类?)
其次,使用 lambda 表达式而不是方法引用进行查找:
public Map<LocationDTO, List<ReferralDetailsDTO>> getWaiting() {
return referralDao.findAll()
.stream()
.map(ReferralDetailsDTO::new)
.collect(Collectors.groupingBy(r -> locationDao.findById(r.getLocationId()));
}
关于java - 如何将这些流式映射键从 Longs 转换为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30827236/