LinkedHashMap Class In Java

  • LinkedHashMap class is one of the class of map interface which extends HashMap class and implements Map interface.
  • It is combination of linked list and Hash table implementation of the Map interface and that's why it is called LinkedHashMap.
  • It is maintaining doubly-linked list insertion order in which keys were inserted into the map.
  • It allows to store null elements and optional Map operations are also available.
  • It is non synchronized implementation so if any thread modifies map structurally when map is accessed by multiple threads then it must be synchronized externally.
Important methods of LinkedHashMap class

  • void clear() : It will remove all mappings from map.
  • boolean containsValue(Object value) : It will check for value in map and return true if values exist in map.
  • V get(Object key) : It will return value which is mapped with specified key in map. Else it will return null.
  • protected boolean removeEldestEntry(Map.Entry<K,V> eldest) : It will returns true if this map should remove its eldest entry.
package JAVAExamples;

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

public class ExampleLinkedHashMap {

 public static void main(String[] args) {
  // Create a hash map.
  LinkedHashMap<String, Double> l = new LinkedHashMap<String, Double>();
  // Put elements to the map.
  l.put("Bicycle", new Double(134.33));
  l.put("Car", new Double(353.12));
  l.put("Bus", new Double(-598.23));
  l.put("Train", new Double(193.56));
  l.put("Motorcycle", new Double(39.48));

  // Print LinkedHashMap.
  System.out.println("LinkedHashMap elements are : " + l);

  // Get size of LinkedHashMap.
  System.out.println("Size of LinkedHashMap is : " + l.size());

  // Get value of key.
  System.out.println("Value of Bus is " + l.get("Bus"));

  // Check if LinkedHashMap is empty.
  System.out.println("LinkedHashMap is empty? : " + l.isEmpty());

  // Check of LinkedHashMap has given value or not
  System.out.println("LinkedHashMap has 353.12 value? : "+ l.containsValue(353.12));

  // Check of LinkedHashMap has given key or not
  System.out.println("LinkedHashMap has taxi key? : "+ l.containsKey("taxi"));

  // Iterate over LinkedHashMap.
  Set<Entry<String, Double>> s = l.entrySet();
  // Get an iterator
  Iterator<Entry<String, Double>> i = s.iterator();
  // Display elements
  while (i.hasNext()) {
   Map.Entry m = (Map.Entry);
   System.out.print(m.getKey() + ": ");

Output : 
LinkedHashMap elements are : {Bicycle=134.33, Car=353.12, Bus=-598.23, Train=193.56, Motorcycle=39.48}
Size of LinkedHashMap is : 5
Value of Bus is -598.23
LinkedHashMap is empty? : false
LinkedHashMap has 353.12 value? : true
LinkedHashMap has taxi key? : false
Bicycle: 134.33
Car: 353.12
Bus: -598.23
Train: 193.56
Motorcycle: 39.48

No comments:

Post a Comment