LinkedHashMap is same as HasHMap just additionally maintains the insertion order.
// Java Program to Illustrate the LinkedHashmap Class
// Importing required classes
import java.util.*;
// Main class
public class Main {
// Main driver method
public static void main(String[] args)
{
// Creating an empty LinkedHashMap
Map<String, Integer> hashmap = new LinkedHashMap<>();
// Inserting entries in the Map
// using put() method
hashmap.put("Banana", 100);
hashmap.put("Orange", 200);
hashmap.put("Mango", 300);
hashmap.put("Apple", 400);
// Iterating over Map
for (Map.Entry<String, Integer> e : hashmap.entrySet())
// Printing key-value pairs
System.out.println(e.getKey() + " "+ e.getValue());
}
}
LinkedHashMap can have null key, keeps order
import java.util.LinkedHashMap;
class Main {
public static void main(String[] args) {
// Creating a LinkedHashMap of even numbers
LinkedHashMap<String, Integer> evenNumbers = new LinkedHashMap<>();
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
System.out.println("LinkedHashMap1: " + evenNumbers);
// Creating a LinkedHashMap from other LinkedHashMap
LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>(evenNumbers);
numbers.put("Three", 3);
System.out.println("LinkedHashMap2: " + numbers);
}
}