如何将这些流式映射键从 Longs 转换为对象?
How can I convert these streamed Map keys from Longs to Objects?
我目前有一个看起来像这样的方法:
public Map<Long, List<ReferralDetailsDTO>> getWaiting() {
return referralDao.findAll()
.stream()
.map(ReferralDetailsDTO::new)
.collect(Collectors.groupingBy(ReferralDetailsDTO::getLocationId, Collectors.toList()));
}
}
它 returns 我是位置 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 更改为您相关的 class(是 LocationDTO
还是其他 class?)
其次,使用 lambda 表达式而不是方法引用进行查找:
public Map<LocationDTO, List<ReferralDetailsDTO>> getWaiting() {
return referralDao.findAll()
.stream()
.map(ReferralDetailsDTO::new)
.collect(Collectors.groupingBy(r -> locationDao.findById(r.getLocationId()));
}
我目前有一个看起来像这样的方法:
public Map<Long, List<ReferralDetailsDTO>> getWaiting() {
return referralDao.findAll()
.stream()
.map(ReferralDetailsDTO::new)
.collect(Collectors.groupingBy(ReferralDetailsDTO::getLocationId, Collectors.toList()));
}
}
它 returns 我是位置 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 更改为您相关的 class(是 LocationDTO
还是其他 class?)
其次,使用 lambda 表达式而不是方法引用进行查找:
public Map<LocationDTO, List<ReferralDetailsDTO>> getWaiting() {
return referralDao.findAll()
.stream()
.map(ReferralDetailsDTO::new)
.collect(Collectors.groupingBy(r -> locationDao.findById(r.getLocationId()));
}