John Lexus
John Lexus

Reputation: 3626

Using Collectors.toMap to return a LinkedHashMap

How can I convert this:

return this.subjects.entrySet()
            .stream()
            .collect(Collectors.toMap(e -> getArtistryCopy(e.getKey()), Map.Entry::getValue));

To return a LinkedHashMap instead of a map?

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() returns a copy of an AbstractArtistry (which is the key).

Upvotes: 12

Views: 8207

Answers (1)

rgettman
rgettman

Reputation: 178263

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));

Upvotes: 17

Related Questions