Home >Java >javaTutorial >How to Maintain Insertion Order in a Java HashMap?

How to Maintain Insertion Order in a Java HashMap?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 06:41:02695browse

How to Maintain Insertion Order in a Java HashMap?

Preserve Insertion Order in HashMap

The HashMap data structure in Java is designed to provide efficient storage and retrieval of key-value pairs. However, it does not maintain the insertion order of the elements. This can be problematic when the order of elements is significant.

LinkedHashMap: Maintaining Insertion Order

To preserve the insertion order, you can use the LinkedHashMap class. It extends the HashMap class and adds an additional feature: it maintains the order of the elements based on their insertion.

Using LinkedHashMap

To preserve the insertion order, simply replace HashMap with LinkedHashMap in your code:

<code class="java">Map<String, String> map = new LinkedHashMap<>();
map.put("first", "value1");
map.put("second", "value2");

for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}</code>

This code will now iterate over the map in the order in which the elements were inserted (i.e., "first" followed by "second").

The above is the detailed content of How to Maintain Insertion Order in a Java HashMap?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn