$show=/label

LinkedHashMap in Java With Example Programs + Java 8 New Methods

SHARE:

A quick guide to LinkedHashMap in Java. LinkedHashMap is used to store the key-value pairs and it preserves the insertion order.

1. Introduction


In this tutorial, We'll learn LinkedHashMap API in java with example programs.

LinkedHashMap is used to store the key-value pairs as similar to the HashMap. But, LinkedHashMap extends HashMap and AbstractMap implements Map interface. The main advantage of LinkedHashMap is it preserves the insertion order that meanwhile iterating it pull the Entry Objects how the order keys are inserted into LinkedHashMap.

Iterating over collection in java

We have discussed HashMap in-depth with all methods examples including java 8 concepts. It is good to go over the HashMap article that makes you answer interview questions on all of its methods.


If you do not understand at any point just leave your question in comments.

LinkedHashMap in Java With Example Programs + Java 8 New Methods




2. LinkedHashMap Key Features


Below are the key factors of LinkedHashMap.


    1. LinkedHashMap stores the key value pairs.
    2. LinkedHashMap uses the internally Double LinkedList.
    3. LinkedHashMap preserves the insertion order and this order is done using Linked List which holds the address of the next Entry object.
    4. LinkedHashMap does not allow duplicate keys
    5. LinkedHashMap allows only one null key and allows multiple null values.
    6. LinkedHashMap is not synchronized
    7. LinkedHashMap has all features of HashMap except holding the insertion order.

3. Internals

3.1 Hierarchy

Below are the classes and interfaces that are involved in implementation.

java.lang.Object
java.util.AbstractMap<K,V>
java.util.HashMap<K,V>
java.util.LinkedHashMap<K,V> 

3.2 Class declaration:


public class LinkedHashMap<K,V>
    extends HashMap<K,V>
    implements Map<K,V>

3.3 Entry class


Below is the Entry class implementation and it is extending HashMap.Node class. It has two references for Entry type those are to hold before and after entry refs. If a key/value is added to the map and immediately it will be added with before and after entry object references.

static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    Entry(int hash, K key, V value, Node<K,V> next) {
        super(hash, key, value, next);
    }
}

4. Creating LinkedHashMap Objects


LinkedHashMap has 5 constructors to create its object.

Way 1: Creates an empty map with size 16.
Way 2: With an initial capacity
Way 3: Creating from an existing map
Way 4: With the size and load factor
Way 5: With size, load factor and access order. true for accessing order and false for insertion order.

// creating LinkedHashMap way
LinkedHashMap<Integer, String> way1 = new LinkedHashMap<>();

// way 2
LinkedHashMap<Integer, String> way2 = new LinkedHashMap<>(25);

// way 3
LinkedHashMap<Integer, String> way3 = new LinkedHashMap<>(way2);

// way 4
LinkedHashMap<Integer, String> way4 = new LinkedHashMap<>(50, 0.5f);

// way 5
LinkedHashMap<Integer, String> way5 = new LinkedHashMap<>(75, 0.75f, false);

5. LinkedHashMap Methods


This gets all methods of the HashMap but the below are directly from LinkedHashMap.


  • clear(): Removes all of the mappings from this map.
  • containsValue(Object value): Returns boolean value true if the specified value is present in the map else returns false.
  • entrySet(): Returns a Set of Entry&lt;K, V&gt; objects. Returned Set is tightly linked to the underlying map. If the Map is modified then the returned Set will be reflected with modifications.
  • forEach(BiConsumer biconsumer): Executes the BiConsumer logic to each key-value pair in the map.
  • get(Object key): Returns the value for the specified key. Returns null if the key is not present in the map.
  • getOrDefault(Object key, V defaultValue): Returns the value for the specified key. If key does not exits then return the default value that we have passed.
  • keySet(): Returns all keys in the form of Set.
  • removeEldestEntry(Map.Entry<K,V> eldest): Returns true if this map should remove its eldest entry
  • replaceAll(BiFunction function): BiFunction logic is executed for all keys and returned value will be updated as a new value in the map for each key.
  • values(): Returns all values as Collection


You may get a question

why only the above methods are implemented as part of LinkedHashMap instead of using from HashMap class?

Answer: As mentioned earlier, This class holds pointers as below. If any methods that are needed to interact with these set of pointers those methods are added as part of LinkedHashMap.

transient LinkedHashMap.Entry<K,V> head;
transient LinkedHashMap.Entry<K,V> tail;

Entry<K,V> before, after;

final boolean accessOrder;

6. LinkedHashMap All Methods Example

Below is the example program for all methods.

package com.java.w3schools.blog.linkedhashmap;

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

public class LinkedHashMapExample {

 public static void main(String[] args) {

  // creating LinkedHashMap way
  LinkedHashMap<Integer, String> way1 = new LinkedHashMap<>();

  // way 2
  LinkedHashMap<Integer, String> way2 = new LinkedHashMap<>(25);

  // way 3
  LinkedHashMap<Integer, String> way3 = new LinkedHashMap<>(way2);

  // way 4
  LinkedHashMap<Integer, String> way4 = new LinkedHashMap<>(50, 0.5f);

  // way 5
  LinkedHashMap<Integer, String> way5 = new LinkedHashMap<>(75, 0.75f, false);

  // Adding values to LinkedHashMap
  System.out.println("\nput example");
  way5.put(111, "One");
  way5.put(222, "Two");
  way5.put(333, "Three");
  way5.put(444, "Four");
  way5.put(555, "Five");

  String value111 = way5.get(111);
  System.out.println("value of key 111 : " + value111);

  // getOrDefault example
  System.out.println("\ngetOrDefault example");
  String valueDefault = way5.getOrDefault(5000, "No Key Found");
  System.out.println("get default value : " + valueDefault);

  String value333 = way5.compute(333, (k, v) -> (v + " - " + k));
  System.out.println("compute example : " + value333);

  // containsKey example
  System.out.println("\ncontainsKey example");
  boolean key555Present = way5.containsKey(555);
  System.out.println("555 key present : " + key555Present);

  // forEach example
  System.out.println("\nforEach example");
  way5.forEach((key, value) -> System.out.println("key - " + key + ", Value - " + value));

  // containsValue example
  System.out.println("\ncontainsValue example");
  System.out.println(way5.containsValue("Five"));

  // entrySet example
  System.out.println("\nentrySet example");
  Set<Entry<Integer, String>> s = way5.entrySet();

  Iterator<Entry<Integer, String>> it = s.iterator();

  while (it.hasNext()) {
   Entry<Integer, String> e = it.next();
   System.out.println(e.getKey() + " ---- " + e.getValue());
  }

  // keySet example
  System.out.println("\nkeySet example");
  Set<Integer> keySet = way5.keySet();

  Iterator<Integer> keyIterator = keySet.iterator();
  while (keyIterator.hasNext()) {
   System.out.println(keyIterator.next());
  }

  // replaceAll example
  System.out.println("\n replaceAll example");
  way5.replaceAll((k, v) -> (k + v));
  System.out.println(way5);
  
  
  
  // clear() example
  way5.clear();
  System.out.println(way5.size());

  
 }

}

Output:

put example
value of key 111 : One

getOrDefault example
get default value : No Key Found
compute example : Three - 333

containsKey example
555 key present : true

forEach example
key - 111, Value - One
key - 222, Value - Two
key - 333, Value - Three - 333
key - 444, Value - Four
key - 555, Value - Five

containsValue example
true

entrySet example
111 ---- One
222 ---- Two
333 ---- Three - 333
444 ---- Four
555 ---- Five

keySet example
111
222
333
444
555

 replaceAll example
{111=111One, 222=222Two, 333=333Three - 333, 444=444Four, 555=555Five}
0

7. Conclusion


In this article, We've seen What is LinkedHashMap API and What is the importance. When we should use this? Shown example programs for all its methods.

If you want to store a key-value pairs and insertion order needs to be preserved then we should go with this. This is similar to the HashMap except it holds the order of insertion.

GitHub

Ref API

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: LinkedHashMap in Java With Example Programs + Java 8 New Methods
LinkedHashMap in Java With Example Programs + Java 8 New Methods
A quick guide to LinkedHashMap in Java. LinkedHashMap is used to store the key-value pairs and it preserves the insertion order.
https://1.bp.blogspot.com/-HX10Kf3itdE/XojDYW3uoDI/AAAAAAAACcA/y5e_lFAjDm48r52Z0SGQ6pljyKyiGNzgACLcBGAsYHQ/s640/LinkedHashMap%2Bin%2BJava%2BWith%2BExamples%2B%252B%2BJava%2B8%2BNew%2BMethods.jpeg
https://1.bp.blogspot.com/-HX10Kf3itdE/XojDYW3uoDI/AAAAAAAACcA/y5e_lFAjDm48r52Z0SGQ6pljyKyiGNzgACLcBGAsYHQ/s72-c/LinkedHashMap%2Bin%2BJava%2BWith%2BExamples%2B%252B%2BJava%2B8%2BNew%2BMethods.jpeg
JavaProgramTo.com
https://www.javaprogramto.com/2020/04/java-linkedhashmap.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/04/java-linkedhashmap.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content