使用Collectors.toMap返回LinkedHashMap [英] Using Collectors.toMap to return a LinkedHashMap
问题描述
我该如何转换:
return this.subjects.entrySet()
.stream()
.collect(Collectors.toMap(e -> getArtistryCopy(e.getKey()), Map.Entry::getValue));
要返回LinkedHashMap而不是地图?
To return a LinkedHashMap instead of a map?
如果您需要知道, this.subjects
是 LinkedHashMap< AbstractArtistries,ArrayList< AbstractCommand>>
.AbstractArtistry和command是我制作的两个自定义对象.我需要维持订单.
If you need to know, this.subjects
is a LinkedHashMap<AbstractArtistries, ArrayList<AbstractCommand>>
. AbstractArtistry and command are two custom objects I made. I need the order to be maintained.
getArtistryCopy()
返回AbstractArtistry的副本(这是键).
getArtistryCopy()
returns a copy of an AbstractArtistry (which is the key).
推荐答案
You can use the overload of Collectors.toMap
that accepts a Supplier
for the Map
. It also takes a merge
function that how to resolve collisions between duplicate keys.
return this.subjects.entrySet()
.stream()
.collect(Collectors.toMap(e -> getArtistryCopy(e.getKey()),
Map.Entry::getValue,
(val1, val2) -> yourMergeResultHere,
LinkedHashMap::new));
这篇关于使用Collectors.toMap返回LinkedHashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!