Sobes.tech
Junior — Middle

Can you list implementations of the Map interface that preserve insertion order?

sobes.tech AI

Answer from AI

In Java, there are several implementations of the Map interface that preserve the order of element insertion:

  • LinkedHashMap — preserves the insertion order of elements and can also maintain access order (if access-order mode is enabled).

Other implementations, such as HashMap, do not guarantee order, while TreeMap sorts elements by key but does not preserve insertion order.

Example of using LinkedHashMap:

Map<String, Integer> map = new LinkedHashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);

// Iteration will preserve the order: one, two, three
for (String key : map.keySet()) {
    System.out.println(key);
}
Can you list implementations of the Map interface… - sobes.tech