Elements are inserted into a list in order of insertion in hashmap

How to Maintain Insertion Order of the Elements in Java HashMap?

When elements get from the HashMap due to hashing the order they inserted is not maintained while retrieval. We can achieve the given task using LinkedHashMap. The LinkedHashMap class implements a doubly-linked list so that it can traverse through all the elements.

Example:

Input : HashMapInput = {c=6, a=1, b=2} Output: HashMapPrint = {c=6, a=1, b=2} Input : HashMapInput = {"first"=1, "second"=3} Output: HashMapPrint = {"first"=1, "second"=3}

Syntax:

public LinkedHashMap(Map m)

It creates an object of the LinkedHashMap class with the same mappings specified in the original Map object.



Order Not Maintain Here: HashMap Implementation:




// Java Program to maintain insertion order
// of the elements in HashMap
// Using HashMap (Order not maintain)
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[])
{
// creating a hashmap
HashMap<String, String> hm = new HashMap<>();
// putting elements
hm.put("01", "aaaaaaa");
hm.put("03", "bbbbbbb");
hm.put("04", "zzzzzzz");
hm.put("02", "kkkkkkk");
System.out.println("Iterate over original HashMap");
// printing hashmap
for (Map.Entry<String, String> entry :
hm.entrySet()) {
System.out.println(entry.getKey() + " => "
+ ": " + entry.getValue());
}
}
}
Output Iterate over original HashMap 01 => : aaaaaaa 02 => : kkkkkkk 03 => : bbbbbbb 04 => : zzzzzzz

Here, the original insertion order of HashMap is [01, 03, 04, 02], but the output is different [01, 02, 03, 04]. It did not maintain the original insertion order of the elements.

Order Maintain Here: LinkedHashMap implementation




// Java Program to maintain insertion order
// of the elements in HashMap
// LinkedHashMap
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[])
{
// creating a hashmap
HashMap<String, String> hm = new LinkedHashMap<>();
// putting elements
hm.put("01", "aaaaaaa");
hm.put("03", "bbbbbbb");
hm.put("04", "zzzzzzz");
hm.put("02", "kkkkkkk");
// printing LinkedHashMap
System.out.println("Iterate over LinkedHashMap");
for (Map.Entry<String, String> entry :
hm.entrySet()) {
System.out.println(entry.getKey() + " => "
+ ": " + entry.getValue());
}
}
}
Output Iterate over LinkedHashMap 01 => : aaaaaaa 03 => : bbbbbbb 04 => : zzzzzzz 02 => : kkkkkkk

Elements are inserted into a list in order of insertion in hashmap




Article Tags :
Java
Java Programs
Java-LinkedHashMap
Practice Tags :
Java

How to maintain the insertion order of the elements in Java HashMap?

We cannot. The HashMap class does not maintain the order of the elements. This means that It might not return the elements in the same order they were inserted into it. If the application needs the elements to be returned in the same order they were inserted, LinkedHashMap should be used.

The LinkedHashMap class implements a doubly linked list so that it can traverse through all the elements. As per LinkedHashMap Java Doc:

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

In the scenario wherein the HashMap is returned from the third-party library which cannot be changed and application needs ordering of the elements contained in it, a LinkedHashMap object can be created from the HashMap object. The LinkedHashMap class has a special constructor for that purpose which takes a Map as an argument.

1
public LinkedHashMap(Map m)

The above given constructor creates an object of the LinkedHashMap class with the same mappings specified in the original Map object.

Important Note:

The LinkedHashMap object created in this way maintains the insertion order in which the elements were returned from the HashMap while the creation of it (and not the order in which elements were inserted into original HashMap). Let’s see a small example to demonstrate that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.javacodeexamples.collectionexamples;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class HashMapOrderExample {
public static void main(String args[]){
HashMap<string, employee=""> employeeMap = new HashMap<string, employee="">();
employeeMap.put("emp01", new Employee("emp01", "Jason", "IT"));
employeeMap.put("emp03", new Employee("emp03", "Aaron", "Supply Chain"));
employeeMap.put("emp04", new Employee("emp04", "Oliver", "Marketing"));
employeeMap.put("emp02", new Employee("emp02", "Raj", "IT"));
System.out.println("Iterate over original HashMap");
for(Map.Entry<string, employee=""> entry :employeeMap.entrySet()){
System.out.println(entry.getKey() + " => " + ": " + entry.getValue());
}
//convert HashMap to LinkedHashMap
LinkedHashMap<string, employee=""> employeeLinkedHashMap =
new LinkedHashMap<string, employee="">(employeeMap);
System.out.println("");
System.out.println("Iterate over LinkedHashMap");
for(Map.Entry<string, employee=""> entry :employeeLinkedHashMap.entrySet()){
System.out.println(entry.getKey() + " => " + ": " + entry.getValue());
}
}
}

Output

1
2
3
4
5
6
7
8
9
10
11
Iterate over original HashMap
emp01 => : [emp01 : Jason : IT]
emp03 => : [emp03 : Aaron : Supply Chain]
emp02 => : [emp02 : Raj : IT]
emp04 => : [emp04 : Oliver : Marketing]
Iterate over LinkedHashMap
emp01 => : [emp01 : Jason : IT]
emp03 => : [emp03 : Aaron : Supply Chain]
emp02 => : [emp02 : Raj : IT]
emp04 => : [emp04 : Oliver : Marketing]

As you can see, we have inserted the Employee objects in HashMap in [emp01, emp03, emp04, emp02] order. However, when we printed the elements by iterating over HashMap, the order was changed to [emp01, emp03, emp02, emp04]. It did not maintain the original insertionorder of the elements “emp02” and “emp04”.

Then we created a LinkedHashMap object from the original HashMap object and printed it. Which returned the elements in [emp01, emp03, emp02, emp04] order. This is the order in which HashMap returned the elements when LinkedHashMap was created from it. From that pointonwards, LinkedHashMap will keep this insertion order whenever it returns the element (not the original order [emp01, emp03, emp02, emp04]).

Here is the example Employee class used in this example.

This example is a part of the Java Hashmap tutorial.

Please let me know your views in the comments section.

Does TreeMap maintain insertion order?

A TreeMap is a Map that maintains its entries in ascending order, sorted according to the keys' natural ordering, or according to a Comparator provided at the time of the TreeMap constructor argument. The TreeMap class is efficient for traversing the keys in a sorted order.

Which maintains the insertion order?

1) List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list. Set is an unordered collection, it doesn't maintain any order.

Java - The LinkedHashMap Class


Advertisements

Previous Page
Next Page

This class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted.

You can also create a LinkedHashMap that returns its elements in the order in which they were last accessed.

Following is the list of constructors supported by the LinkedHashMap class.

Sr.No.Constructor & Description
1

LinkedHashMap( )

This constructor constructs a default LinkedHashMap.

2

LinkedHashMap(Map m)

This constructor initializes the LinkedHashMap with the elements from the given Map class m.

3

LinkedHashMap(int capacity)

This constructor initializes a LinkedHashMap with the given capacity.

4

LinkedHashMap(int capacity, float fillRatio)

This constructor initializes both the capacity and the fill ratio. The meaning of capacity and fill ratio are the same as for HashMap.

5

LinkedHashMap(int capacity, float fillRatio, boolean Order)

This constructor allows you to specify whether the elements will be stored in the linked list by insertion order, or by order of last access. If Order is true, then access order is used. If Order is false, then insertion order is used.

Apart from the methods inherited from its parent classes, LinkedHashMap defines the following methods −

Sr.No.Method & Description
1

void clear()

Removes all mappings from this map.

2

boolean containsKey(Object key)

Returns true if this map maps one or more keys to the specified value.

3

Object get(Object key)

Returns the value to which this map maps the specified key.

4

protected boolean removeEldestEntry(Map.Entry eldest)

Returns true if this map should remove its eldest entry.