Home » How to Keep the Elements of a Map in the Same Order That They Were Inserted

How to Keep the Elements of a Map in the Same Order That They Were Inserted

group of men forming a libe

Usually, Java developers instantiate Maps using HashMap as implementation. Did you know HashMap doesn’t keep the order of insertion?

Look at the following example:

import java.util.HashMap;
import java.util.Map;

public class MapOrder {

    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();

        map.put(5, "five");
        map.put(4, "four");
        map.put(3, "three");
        map.put(2, "two");
        map.put(1, "one");

        map.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

If we run the example above, the following output will be printed:

1: one
2: two
3: three
4: four
5: five

So, if you want to keep the elements in the order that they were inserted, use another implementation of Map. Use LinkedHashMap, which keeps that order.

When we change the example to:

import java.util.LinkedHashMap;
import java.util.Map;

public class MapOrder {

    public static void main(String[] args) {
        Map<Integer, String> map = new LinkedHashMap<>();

        map.put(5, "five");
        map.put(4, "four");
        map.put(3, "three");
        map.put(2, "two");
        map.put(1, "one");

        map.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

The following output will be printed:

5: five
4: four
3: three
2: two
1: one

Did you notice that it preserved the order of insertion?

So, LinkedHashMap is the right implementation of Map that you need to use when you want to keep the elements in the same order that they were inserted.

If you have any questions, leave a comment or send me a message on my social media.

Leave a Reply

Your email address will not be published. Required fields are marked *