LinkedHashMap Tutorial Java – Complete Programming Example

In this chapter you will learn:

  • What is LinkedHashMap in Java?
  • How to iterate through LinkedHashMap?
  • Programming Example
  • What is LinkedHashMap class in Java?

    LinkedHashMap is a combination of HashTable and Linked List and it stores items based on Key/Value pair. LinkedHashMap doesn’t allow inserting duplicate element. Point about LinkedHashMap are listed below:

    1. It contains values based on key.
    2. It contains only unique elements.
    3. It maintains insertion order as the keys were inserted.
    4. It is same as HashMap instead maintains insertion order.
    5. It maintains Doubly Linked List running through of all its objects.

    How to Initialize LinkedHashMap?

    Methods and Properties

    ConstructorDescription
    LinkedHashMap()It is used to construct a default LinkedHashMap.
    LinkedHashMap(int capacity)It is used to initialize a LinkedHashMap with the given capacity.
    LinkedHashMap(int capacity, float fillRatio)It is used to initialize both the capacity and the fillRatio.
    LinkedHashMap(Map m)It is used to initialize the LinkedHashMap with the elements from the given Map class m.

    Methods

    MethodsDescription
    Object get(Object key)It is used to return the value to which this map maps the specified key.
    void clear()It is used to remove all mappings from this map.
    boolean containsKey(Object key)It is used to return true if this map maps one or more keys to the specified value.

    Programming Example

    Output

    First Methods Printing
    Key is : 22 and Value is : Jack
    Key is : 23 and Value is : Steven
    Key is : 26 and Value is : Clark
    Key is : 18 and Value is : Mathew
    Second Methods Printing
    Key : 22 | Value = Jack
    Key : 23 | Value = Steven
    Key : 26 | Value = Clark
    Key : 18 | Value = Mathew
    Direct Printing
    {22=Jack, 23=Steven, 26=Clark, 18=Mathew}
    Item removed : Clark
    Item Added : null
    {22=Jack, 23=Steven, 18=Mathew, 19=Sarah}
    _

    Summary

    In this chapter I’ve tried to explain LinkedHashMap with complete programming example in java. Almost the programming of all the collections classes are same and there is not too much differences. Once, you learn to write collection programming It gets very easy to learn rest of the collection objects. In the next chapter you will learn TreeMap class in Java.


    Leave a Reply

    Your email address will not be published. Required fields are marked *