Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are:

  1. It contains the values based on the keys.
  2. It maintains the order of insertion.
  3. It contains unique elements.
  4. It contains one null key and multiple null values.
  5. It is not synchronized.
  6. The initial capacity is 16, and the load factor is 0.75f.

Declaration of LinkedHashMap

Constructors in LinkedHashMap:

  1. LinkedHashMap (): This is used to create default LinkedHashMap constructor.
  2. LinkedHashMap (int capacity): It is used to set the LinkedHashMap with specified capacity.
  3. LinkedHashMap (int capacity, float Loadfactor): It is used to set the LinkedHashMap with capacity and Load factor.
  4. LinkedHashMap (Map m): This is used to set the LinkedHashMap with elements from the given Map.
  5. LinkedHashMap (int capacity, float Load factor, boolean order): This is used to set the LinkedHashMap with capacity and Loadfactor along with specified order.

Difference between LinkedHashMap and LinkedHashSet:

LinkedHashMap

LinkedHashSet

1. LinkedHashMap implements Map interface and inherits HashMap class. 1. LinkedHashSet implements Set interface and inherits HashSet class.
2. It replaces the value with duplicate keys. 2. It does not change the original value.
3. It was mapping the keys to values. 3. It simply stores the values.
4. It enables one null key and multiple null values. 4. It permits only one null value.
5. It consists of five types of constructors. 5. It consists of four types of constructors.
6.Declaration:  LinkedHashMap<Integer, String> lm= new LinkedHashMap<Integer, String> (); 6.Declaration:

LinkedHashSet<String> lh= new LinkedHashSet<String> ();

Methods of LinkedHashMap:

  1. clear (): It is used to clear all the mapping from the map.

Example:

Output:

  1. containsKey (Object K): It returns true if the specified key is present on the map.

Example:

Output:

  1. get (Object K): It is used to get the value of a particular key from the map.

Example:

Output:

  1. removeEldestEntry (Map.Entry eldest): This method is used to remove the eldest entry from the map.

Example:

Output:

  1. forEach (Biconsumer<K, V> action): It completes the given action of each entry in the map until all entries have been processed throws the exception.

Example:

Output:

6. keySet (): It returns the set of keys in the map.

Example:

Output:

  1. Values (): This returns the collections of values in the map.

Example:

Output:

  1. entrySet (): This returns the Set view of the whole mapping in the map.

Example:

Output:

  1. getOrDeafult (Object key, V default Values): This method returns the value which is mapped with particular key. The default value if map cannot contain the mapping of the key.

Example:

Output: