Skip to content
Advertisement

How do I keep the iteration order of a List when using Collections.toMap() on a stream?

I am creating a Map from a List as follows:

JavaScript

I want to keep the same iteration order as was in the List. How can I create a LinkedHashMap using the Collectors.toMap() methods?

Advertisement

Answer

The 2-parameter version of Collectors.toMap() uses a HashMap:

JavaScript

To use the 4-parameter version, you can replace:

JavaScript

with:

JavaScript

Or to make it a bit cleaner, write a new toLinkedMap() method and use that:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement