Master java skills

LinkedHashMap in Java

We have seen HashMap examples and its working. There are two more map classes: LinkedHashmap and TreeMap. Let’s talk about them as well.

LinkedHashMap

LinkedHashmap extends HashMap. The difference between LinkedHashmap and HashMap is that LinkedHashmap maintains insertion order of key-value pair. So, whenever, we want our map to maintain insertion order of entries, go for LinkedHashMap. Let’s see one example

We will create a class Footballer with id and name as two attributes.

package com.javatrainingschool;

public class Footballer {
	
	private int id;
	private String name;
	public Footballer(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	@Override
	public String toString() {
		return "Footballer [id=" + id + ", name=" + name + "]";
	}

        //getter and setter methods
}  

Main class

package com.javatrainingschool;

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

public class LinkedHashMapExample {
	
	public static void main(String[] args) {
		
		Footballer f1 = new Footballer(1, "Christiano Ronaldo");
		Footballer f2 = new Footballer(2, "Lionel Messi");
		Footballer f3 = new Footballer(3, "Pele");
		Footballer f4 = new Footballer(4, "Diego Maradona");
		
		Map<Integer, Footballer> map = new LinkedHashMap<Integer, Footballer>();
		map.put(4, f4);
		map.put(2, f2);
		map.put(1, f1);
		map.put(3, f3);
        
		//entries will be printed in the order Maradona, Messi, Ronaldo, and Pele
		for(Entry<Integer, Footballer> entry : map.entrySet()) {
			System.out.println(entry.getValue());	
		}
	}
}
Output :

Footballer [id=4, name=Diego Maradona]
Footballer [id=2, name=Lionel Messi]
Footballer [id=1, name=Christiano Ronaldo]
Footballer [id=3, name=Pele]