Home > Java > javaTutorial > body text

How to Preserve Insertion Order in HashMaps in Java?

Susan Sarandon
Release: 2024-11-03 05:49:03
Original
400 people have browsed it

How to Preserve Insertion Order in HashMaps in Java?

Preserving Insertion Order in HashMaps using LinkedHashMap

When working with HashMaps in Java, preserving the order of inserted elements is crucial in certain scenarios. By default, HashMaps do not maintain the insertion order, resulting in a random ordering during iteration. To address this issue, you can utilize the LinkedHashMap class.

LinkedHashMap extends HashMap and offers the same functionality with an additional feature: it maintains the insertion order of the elements. This means that when you iterate over a LinkedHashMap, the elements are returned in the order they were initially inserted into the map.

To create a LinkedHashMap, simply instantiate it as follows:

<code class="java">import java.util.LinkedHashMap;

LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();</code>
Copy after login

Now, you can add elements to the LinkedHashMap as you would with a regular HashMap:

<code class="java">linkedHashMap.put("key1", "value1");
linkedHashMap.put("key2", "value2");</code>
Copy after login

However, when you iterate over the LinkedHashMap:

<code class="java">for (String key : linkedHashMap.keySet()) {
    System.out.println(key);
}</code>
Copy after login

The keys will be printed in the order they were inserted: "key1" followed by "key2".

Using LinkedHashMap ensures that the insertion order of elements is preserved, making it suitable for situations where maintaining the chronological sequence of data is essential.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template