英文:
how to collect to LinkedHashMap in java 8
问题
目前,我们正在通过以下方式将repository.findAll()
返回的列表转换为Map:
Map<Long, FooDto> fooMap = fooRepository.findAll()
.stream()
.map(fooDomainToDtoMapper::mapDomainToDto)
.collect(Collectors.toMap(fooDto::getfooId, foo -> foo));
但我们希望保留repository.findAll()
返回的顺序。我们想要按降序返回记录,然后通过类似以下方式将其收集到LinkedHashMap
中:
Map<Long, FooDto> fooMap = fooRepository.findAll(Sort.by(Sort.Direction.DESC, "name"))
.stream()
.map(fooDomainToDtoMapper::mapDomainToDto)
// 尝试类似这样操作:
.collect(Collectors.toMap(fooDto::getfooId, foo -> foo, LinkedHashMap::new));
如果我们尝试将上述降序结果在普通的Collectors.toMap
中收集,那么排序查询将毫无效果,最终结果看起来就像普通的选择查询。
英文:
Currently we are converting list returned by repository.findAll()
into the Map by doing:
Map<Long, FooDto> fooMap=fooRepository.findAll()
.stream()
.map(fooDomainToDtoMapper::mapDomainToDto)
.collect(Collectors.toMap(fooDto::getfooId, foo -> foo));
But we want to preserve the order returned by the repository.findAll()
. We want to return the records in the descending order and then collect it to the LinkedHashmap
by doing something like :
Map<Long, FooDto> fooMap= fooRepository.findAll(Sort.by(Sort.Direction.DESC, "name"))
.stream()
.map(fooDomainToDtoMapper::mapDomainToDto)
//trying to do something like:
.collect(Collectors.toMap(fooDto::getfooId, foo -> foo,LinkedHashMap::new));
If we try to collect the above descending order result in the normal Collectors.toMap
then sorted query has no effect at all, it is looking like normal select in the final result.
答案1
得分: 3
如果您想要为 Map
传递一个供应商,您还必须传递一个合并函数:
Map<Long, FooDto> fooMap = fooRepository.findAll(Sort.by(Sort.Direction.DESC, "name"))
.stream()
.map(fooDomainToDtoMapper::mapDomainToDto)
.collect(Collectors.toMap(FooDto::getFooId,
Function.identity(),
(v1, v2) -> v1,
LinkedHashMap::new));
英文:
If you want to pass a supplier for the Map
, you must pass a merge function too:
Map<Long, FooDto> fooRepository.findAll(Sort.by(Sort.Direction.DESC, "name"))
.stream()
.map(fooDomainToDtoMapper::mapDomainToDto)
.collect(Collectors.toMap(fooDto::getfooId,
Function.identity(),
(v1,v2)->v1,
LinkedHashMap::new));
答案2
得分: 0
尝试这样做:
.stream()
.map(fooDomainToDtoMapper::mapDomainToDto)
.collect(LinkedHashMap::new,
(map, fooDto) -> map.put(fooDto.getfooId(), fooDto),
Map::putAll);
英文:
Try this:
.stream()
.map(fooDomainToDtoMapper::mapDomainToDto)
.collect(LinkedHashMap::new,
(map, fooDto) -> map.put(fooDto.getfooId(), fooDto),
Map::putAll);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论