Home  >  Core Java

Example of LinkedHashMap in Java

By Arvind Rai, June 09, 2013
java.util.LinkedHashMap maintains the order in which the elements are added. LinkedHashMap does not maintain the order. Performance of LinkedHashMap is slower than HashMap. LinkedHashMap should be used when we want to maintain the order. LinkedHashMap is not synchronized by default but can be synchronized as below.
 Map map = Collections.synchronizedMap(new LinkedHashMap());
 


LinkedHashMapDemo.java
package com.concretepage.util;
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapDemo {
    public static void main(String[] args) {
        Map<Integer,User> map = new LinkedHashMap<Integer,User>();
        User u1 = new User("A");
        User u2 = new User("B");
        User u3 = new User("C");
        map.put(1, u1);
        map.put(2, u2);
        map.put(3, u3);
        System.out.println(map.size());
        System.out.println(map.get(1).name);
        //iterate LinkedHashMap
        for(Map.Entry<Integer,User> mapEntry : map.entrySet() ){
            System.out.println(mapEntry.getKey() +" "+mapEntry.getValue().name);
        }
    }
}
class User {
    public String name;
    public User(String name) {
        this.name = name;
    }
 }
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us