English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/)

Java Reader/Writer

Java other topics

Java LinkedHashMap

In this tutorial, we will learn about the Java LinkedHashMap class and its operations with the help of examples.

The LinkedHashMap class in the Java collection framework providesMap interfacehash table and linked list implementation.

LinkedHashMap inheritsHashMapclass to store its entries in a hash table. It maintains a doubly linked list internally among all entries to sort the entries.

Create a LinkedHashMap

To create a doubly linked list, we must first import the java.util.LinkedHashMap package. After importing the package, we can use the following method to create a doubly linked list in Java.

//The initial capacity of LinkedHashMap is8The load factor is 0.6
LinkedHashMap<Key, Value> numbers = new LinkedHashMap<>();8, 0.6f);

In the above code, we created a LinkedHashMap named numbers.

Here,

  • Key - The unique identifier used to associate each element (value) in the map

  • Value - The elements associated with the keys in the map

Note new LinkedHashMap<>(8,0.6) This part. Here, the first parameter is capacity, and the second parameter is loadFactor.

  • capacity -  The capacity of this doubly linked list is8. This means that it can store8entries.

  • loadFactor- The load factor of this doubly linked list is 0.6. This means that every time the hash map is filled60% when an entry will be moved to a new hash table whose size is twice the size of the original hash table.

Default capacity and load factor

You do not need to define its capacity and load factor to create a doubly linked list. For example,

//LinkedHashMap with default capacity and load factor
LinkedHashMap<Key, Value> numbers1 = new LinkedHashMap<>();

By default,

  • The capacity of the doubly linked list will be 16

  • The load factor will be 0.75

Note: The LinkedHashMap class also allows us to define the order of entries. For example

//LinkedHashMap with specified order
LinkedHashMap<Key, Value> numbers2 = new LinkedHashMap<>(capacity, loadFactor, accessOrder);

Here, accessOrder is a boolean value. The default value is false. In this case, the entries in the doubly linked list will be sorted according to their insertion order.

However, if the accessOrder value is true, the entries in the doubly linked list will be sorted in the order of the most recent access.

Create LinkedHashMap from other doubly linked list

Below is a doubly linked list containing all elements of the other mappings.

import java.util.LinkedHashMap;
class Main {
    public static void main(String[] args) {
        //Create LinkedHashMap of even numbers
        LinkedHashMap<String, Integer> evenNumbers = new LinkedHashMap<>();
        evenNumbers.put("Two", 2);
        evenNumbers.put("Four", 4);
        System.out.println("LinkedHashMap1: " + evenNumbers);
        //Create LinkedHashMap from other LinkedHashMap
        LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>(evenNumbers);
        numbers.put("Three", 3);
        System.out.println("LinkedHashMap2: " + numbers);
    {}
{}

Output result

LinkedHashMap1: {Two=2, Four=4{}
LinkedHashMap2: {Two=2, Four=4Three=3{}

Methods of LinkedHashMap

This LinkedHashMap class provides various operation methods on the map.

inserts the element into LinkedHashMap

  • put() - inserts the specified key/value mapping inserted into the mapping

  • putAll() -inserts all entries from the specified mapping into this map

  • putIfAbsent() -if the specified key does not exist in the map, then insert the specified key/value mapping inserted into the map

For example,

import java.util.LinkedHashMap;
class Main {
    public static void main(String[] args) {
        // Creating LinkedHashMap of even numbers
        LinkedHashMap<String, Integer> evenNumbers = new LinkedHashMap<>();
        // using put()
        evenNumbers.put("Two", 2);
        evenNumbers.put("Four", 4);
        System.out.println("original LinkedHashMap: ") + evenNumbers);
        // using putIfAbsent()
        evenNumbers.putIfAbsent("Six", 6);
        System.out.println("updated LinkedHashMap(): ") + evenNumbers);
        //Creating LinkedHashMap of numbers
        LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>();
        numbers.put("One", 1);
        // using putAll()
        numbers.putAll(evenNumbers);
        System.out.println("new LinkedHashMap: ") + numbers);
    {}
{}

Output result

original LinkedHashMap: {Two=2, Four=4{}
updated LinkedHashMap: {Two=2, Four=4, Six=6{}
new LinkedHashMap: {One=1Two=2, Four=4, Six=6{}

to access LinkedHashMap elements

1.using entrySet(), keySet() and values()

  • entrySet() -returns all keys in the mapping/collection of value mappings

  • keySet() - returns the collection of all keys in the map

  • values() - returns the collection of all values in the map

For example,

import java.util.LinkedHashMap;
class Main {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>();
        numbers.put("One", 1);
        numbers.put("Two", 2);
        numbers.put("Three", 3);
        System.out.println("LinkedHashMap: {" + numbers);
        // using entrySet()
        System.out.println("Key")/Value mapping: + numbers.entrySet());
        // using keySet()
        System.out.println("Keys(键): ") + numbers.keySet());
        // using values()
        System.out.println("Values(值): ") + numbers.values())
    {}
{}

Output result

LinkedHashMap: {One=1Two=2Three=3{}
Key/Value mapping: [One=1Two=2Three=3]
Keys (Keys): [One, Two, Three]
Values (Values): [1, 2, 3]

2.Using get() and getOrDefault()

  • get() - Returns the value associated with the specified key. If the key is not found, it returns null.

  • getOrDefault() - Returns the value associated with the specified key. If the key is not found, it returns the specified default value.

For example,

import java.util.LinkedHashMap;
class Main {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>();
        numbers.put("One", 1);
        numbers.put("Two", 2);
        numbers.put("Three", 3);
        System.out.println("LinkedHashMap: {" + numbers);
        // Using get()
        int value1 = numbers.get("Three");
        System.out.println("Return numbers: " + value1);
        // Using getOrDefault()
        int value2 = numbers.getOrDefault("Five", 5);
        System.out.println("Return numbers: " + value2);
    {}
{}

Output result

LinkedHashMap: {One=1Two=2Three=3{}
Return numbers: 3
Return numbers: 5

Delete LinkedHashMap elements

  • remove(key) - Returns and removes the item associated with the specified key from the map.

  • remove(key, value) - An entry is removed from the map only when the specified key key is mapped to the specified value value and a boolean value is returned.

For example,

import java.util.LinkedHashMap;
class Main {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>();
        numbers.put("One", 1);
        numbers.put("Two", 2);
        numbers.put("Three", 3);
        System.out.println("LinkedHashMap: {" + numbers);
        //Method with a single parameter for deletion
        int value = numbers.remove("Two");
        System.out.println("Deleted value: " + value);
        //Method with two parameters for deletion
        boolean result = numbers.remove("Three", 3);
        System.out.println("Entry3Was it deleted? " + result);
        System.out.println("Updated LinkedHashMap: {" + numbers);
    {}
{}

Output result

LinkedHashMap: {One=1Two=2Three=3{}
Deleted value: 2
Entry3Was it deleted? True
Updated LinkedHashMap: {One=1{}

Other LinkedHashMap Methods

MethodDescription
clear()Delete all entries from the map
containsKey()Check if the map contains the specified key and return a boolean value
containsValue()Check if the map contains the specified value and return a boolean value
size()Return the size of the map
isEmpty()Check if the map is empty and return a boolean value

Differences Between LinkedHashMap and HashMap

Both LinkedHashMap and HashMap implement the Map interface. However, there are some differences between them.

  • LinkedHashMap maintains a doubly linked list internally. Therefore, it maintains the insertion order of its elements.

  • The LinkedHashMap class requires more storage space than HashMap. This is because LinkedHashMap maintains a linked list internally.

  • The performance of LinkedHashMap is slower than HashMap.