Home > Java > javaTutorial > How Do I Preserve Insertion Order in Java HashMaps?

How Do I Preserve Insertion Order in Java HashMaps?

Patricia Arquette
Release: 2024-11-03 04:33:03
Original
281 people have browsed it

How Do I Preserve Insertion Order in Java HashMaps?

Preserving Insertion Order in HashMaps

When working with HashMaps, it's common to encounter situations where the order of elements during iteration is inconsistent with their insertion order. However, in certain use cases, maintaining the insertion order is crucial. To address this need, the Java Collections Framework provides the LinkedHashMap.

Solution: LinkedHashMap

The LinkedHashMap class extends the HashMap class. It retains the insertion order by maintaining an internal doubly-linked list that connects the elements in the order they are inserted. When iterating over a LinkedHashMap, the elements are returned in the same order in which they were added.

Example:

<code class="java">Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "One");
map.put(3, "Three");
map.put(2, "Two");

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

Output:

1: One
3: Three
2: Two
Copy after login

As you can see, the elements are printed in the order they were inserted (1, 3, 2).

Conclusion:

By utilizing LinkedHashMap, you can preserve the insertion order of elements in a HashMap. This feature is particularly useful for scenarios where the order of the elements is critical for the correct operation of your application.

The above is the detailed content of How Do I Preserve Insertion Order in Java HashMaps?. 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