Maintain Insertion Order Using Java LinkedHashMap

 Posted On  | Yashwant Chavan 

LinkedHashMap Insertion Order example demonstrate, How LinkedHashMap works and maintain the insertion order of elements, also learn how to iterate the LinkedHashMap using java.

It is ordered version of map implementation Based on linked list and hashing data structures. Find official documentation about LinkedHashMap on oracle website.

In below code we are going to insert city Name as Key and Value in the order "Mumbai", "Pune" and Nashik. As it is LinkedHashMap collection, it is going to maintain the key insertion order. While retrieving the data back you will get it in the same order as "Mumbai", "Pune" and "Nashik".

LinkedHashMap Example

A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view.

These Map.Entry objects are valid only for the duration of the iteration; more formally, the behaviour of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.

package com.technicalkeeda.app;

import java.util.LinkedHashMap;
import java.util.Map;

public class CollectionDemo {

    public static void main(String[] args) {
        Map < String, String > cities = new LinkedHashMap < String, String > ();
        cities.put("Mumbai", "Mumbai");
        cities.put("Pune", "Pune");
        cities.put("Nashik", "Nashik");

        for (Map.Entry city: cities.entrySet()) {
            System.out.println("Key:- " + city.getKey() + " Value :- " + city.getValue());
        }
    }

}

Output

Key:- Mumbai Value :- Mumbai
Key:- Pune Value :- Pune
Key:- Nashik Value :- Nashik

Iterator LinkedHashMap

Set citiesSet = cities.entrySet();
Iterator itr = citiesSet.iterator();
while (itr.hasNext()) {
    System.out.println("Cities:- " + itr.next());
}


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0308 seconds.