Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 723
John Lexus Avatar asked Apr 04 '18 00:04

John Lexus


1 Answers

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));
like image 169
rgettman Avatar answered Oct 22 '22 07:10

rgettman