使用 Collectors.toMap 到 return LinkedHashMap
Using Collectors.toMap to return a LinkedHashMap
如何转换:
return this.subjects.entrySet()
.stream()
.collect(Collectors.toMap(e -> getArtistryCopy(e.getKey()), Map.Entry::getValue));
要 return LinkedHashMap 而不是地图?
如果你需要知道,this.subjects
是一个LinkedHashMap<AbstractArtistries, ArrayList<AbstractCommand>>
。 AbstractArtistry 和 command 是我制作的两个自定义对象。我需要维持秩序。
getArtistryCopy()
returns 一个 AbstractArtistry 的副本(这是关键)。
您可以使用 the overload of Collectors.toMap
接受 Supplier
作为 Map
。它还需要一个 merge
函数来解决重复键之间的冲突。
return this.subjects.entrySet()
.stream()
.collect(Collectors.toMap(e -> getArtistryCopy(e.getKey()),
Map.Entry::getValue,
(val1, val2) -> yourMergeResultHere,
LinkedHashMap::new));
如何转换:
return this.subjects.entrySet()
.stream()
.collect(Collectors.toMap(e -> getArtistryCopy(e.getKey()), Map.Entry::getValue));
要 return LinkedHashMap 而不是地图?
如果你需要知道,this.subjects
是一个LinkedHashMap<AbstractArtistries, ArrayList<AbstractCommand>>
。 AbstractArtistry 和 command 是我制作的两个自定义对象。我需要维持秩序。
getArtistryCopy()
returns 一个 AbstractArtistry 的副本(这是关键)。
您可以使用 the overload of Collectors.toMap
接受 Supplier
作为 Map
。它还需要一个 merge
函数来解决重复键之间的冲突。
return this.subjects.entrySet()
.stream()
.collect(Collectors.toMap(e -> getArtistryCopy(e.getKey()),
Map.Entry::getValue,
(val1, val2) -> yourMergeResultHere,
LinkedHashMap::new));