Java LinkedHashMap class

Java LinkedHashMap is a class that extends the HashMap class and maintains a linked list of the entries in the map. This linked list defines the iteration order, which is normally the order in which keys were inserted into the map (insertion order).

Like HashMap, LinkedHashMap provides constant-time performance for the basic operations (add, remove, and get) as long as the hash function evenly distributes the elements among the buckets, but LinkedHashMap adds the additional overhead of maintaining the linked list.

One of the main advantages of using LinkedHashMap is that it allows us to iterate through the elements in the order they were added to the map, which can be useful in certain scenarios.

LinkedHashMap also provides a few constructors that allow us to specify whether the iteration order should be based on the insertion order or the order of last access. Additionally, it provides some methods that allow us to manipulate the iteration order, such as removeEldestEntry(), which can be used to remove the least recently used entry from the map.

Here’s an example of how to use a LinkedHashMap:

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");

        // iterate through the map in insertion order
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

Output:

key1 : value1
key2 : value2
key3 : value3

LinkedHashMap class declaration:

The declaration of the Java LinkedHashMap class is as follows:

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

This declaration indicates that the LinkedHashMap class is a generic class that takes two type parameters, K and V, which represent the types of the keys and values that will be stored in the map.

The class extends the HashMap class and implements the Map interface, which means that it provides all the methods defined in the Map interface and inherits all the methods and properties of the HashMap class.

The LinkedHashMap class adds additional properties and methods to the ones provided by the HashMap class, such as maintaining the order of insertion and providing methods to manipulate the iteration order.

LinkedHashMap class Parameters:

The Java LinkedHashMap class is a generic class, which means it takes two type parameters:

  • K: the type of the keys stored in the map
  • V: the type of the values stored in the map

Here’s the declaration of the LinkedHashMap class with its type parameters:

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

n addition to the type parameters, the LinkedHashMap class also accepts several parameters in its constructors that allow us to customize its behavior:

  • initialCapacity: specifies the initial capacity of the map, which is the number of buckets allocated for storing the entries. The default value is 16.
  • loadFactor: specifies the load factor of the map, which is the threshold at which the map is resized. When the number of entries exceeds the product of the load factor and the current capacity, the map is resized. The default value is 0.75.
  • accessOrder: specifies whether the iteration order of the map should be based on the order of insertion (false) or the order of access (true). The default value is false.
  • removeEldestEntry: a method that can be overridden to specify whether the eldest entry (the least recently used) should be removed from the map when a new entry is added. By default, this method returns false, which means that the eldest entry is not removed.

Here’s an example of a constructor call that specifies the initial capacity, load factor, and access order:

Map<String, String> map = new LinkedHashMap<>(10, 0.75f, true);

This creates a LinkedHashMap with an initial capacity of 10, a load factor of 0.75, and an access order of true.

Constructors of Java LinkedHashMap class:

The Java LinkedHashMap class provides several constructors to create instances of the class. Here’s an overview of the constructors:

  1. LinkedHashMap(): creates an empty LinkedHashMap instance with the default initial capacity (16) and the default load factor (0.75). The iteration order is based on the order of insertion.
Map<String, Integer> map = new LinkedHashMap<>();
  1. LinkedHashMap(int initialCapacity): creates an empty LinkedHashMap instance with the specified initial capacity and the default load factor (0.75). The iteration order is based on the order of insertion.
Map<String, Integer> map = new LinkedHashMap<>(20);
  1. LinkedHashMap(int initialCapacity, float loadFactor): creates an empty LinkedHashMap instance with the specified initial capacity and load factor. The iteration order is based on the order of insertion.
Map<String, Integer> map = new LinkedHashMap<>(10, 0.5f);
  1. LinkedHashMap(Map<? extends K,? extends V> m): creates a LinkedHashMap instance that contains the same mappings as the specified map. The iteration order is based on the order of insertion.
Map<String, Integer> originalMap = new HashMap<>();
originalMap.put("A", 1);
originalMap.put("B", 2);
Map<String, Integer> newMap = new LinkedHashMap<>(originalMap);
  1. LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder): creates an empty LinkedHashMap instance with the specified initial capacity, load factor, and access order. The access order determines the iteration order: if it’s true, the order is based on access order, otherwise it’s based on insertion order.
Map<String, Integer> map = new LinkedHashMap<>(10, 0.5f, true);

All of these constructors create instances of the LinkedHashMap class with the specified properties, allowing us to customize its behavior according to our needs.

Methods of Java LinkedHashMap class:

The Java LinkedHashMap class provides a number of methods for adding, removing, and accessing elements in the map. Here are some of the most commonly used methods:

  1. put(K key, V value): Associates the specified value with the specified key in the map. If the map already contains a mapping for the key, the old value is replaced by the new one.
Map<String, Integer> map = new LinkedHashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
  1. get(Object key): Returns the value to which the specified key is mapped, or null if the map contains no mapping for the key.
Integer value = map.get("A"); // value = 1
  1. remove(Object key): Removes the mapping for the specified key from the map, if present.
map.remove("B");
  1. clear(): Removes all the mappings from the map.
map.clear();
  1. containsKey(Object key): Returns true if the map contains a mapping for the specified key.
boolean containsKey = map.containsKey("C"); // containsKey = true
  1. containsValue(Object value): Returns true if the map contains at least one mapping with the specified value.
boolean containsValue = map.containsValue(3); // containsValue = true
  1. size(): Returns the number of mappings in the map.
int size = map.size(); // size = 2
  1. keySet(): Returns a Set view of the keys contained in the map.
Set<String> keys = map.keySet();
  1. values(): Returns a Collection view of the values contained in the map.
Collection<Integer> values = map.values();
  1. entrySet(): Returns a Set view of the mappings contained in the map.
Set<Map.Entry<String, Integer>> entries = map.entrySet();

In addition to these methods, the LinkedHashMap class also provides methods for iterating over the entries in the map, manipulating the iteration order, and customizing the behavior of the class, such as forEach(), replace(), compute(), merge(), putIfAbsent(), getOrDefault(), replace(), computeIfAbsent(), and computeIfPresent().

Java LinkedHashMap Example:

Sure! Here’s an example of how to use the LinkedHashMap class in Java:

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a new LinkedHashMap
        Map<String, Integer> map = new LinkedHashMap<>();

        // Add some mappings
        map.put("John", 24);
        map.put("Mary", 28);
        map.put("Peter", 19);
        map.put("Alice", 22);

        // Print the contents of the map
        System.out.println("Initial LinkedHashMap: " + map);

        // Access a value by key
        int age = map.get("Mary");
        System.out.println("Mary's age: " + age);

        // Remove a mapping
        map.remove("Peter");
        System.out.println("LinkedHashMap after removing Peter: " + map);

        // Iterate over the entries in the map
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String name = entry.getKey();
            int value = entry.getValue();
            System.out.println(name + ": " + value);
        }
    }
}

In this example, we create a new LinkedHashMap and add some mappings to it using the put() method. We then print the contents of the map using the System.out.println() method.

Next, we use the get() method to access the value associated with the key “Mary”, and print it to the console. We then remove the mapping for the key “Peter” using the remove() method, and print the contents of the map again.

Finally, we iterate over the entries in the map using a for-each loop, and print the key-value pairs to the console using the getKey() and getValue() methods of the Map.Entry interface.

Java LinkedHashMap Example: Key-Value pair

Sure, here’s an example of using a LinkedHashMap to store key-value pairs:

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a new LinkedHashMap to store student grades
        Map<String, Integer> grades = new LinkedHashMap<>();

        // Add some student grades to the map
        grades.put("Alice", 90);
        grades.put("Bob", 85);
        grades.put("Charlie", 92);
        grades.put("David", 87);

        // Print the grades for each student
        for (Map.Entry<String, Integer> entry : grades.entrySet()) {
            String student = entry.getKey();
            int grade = entry.getValue();
            System.out.println(student + ": " + grade);
        }
    }
}

In this example, we create a new LinkedHashMap called grades to store student grades. We add some student grades to the map using the put() method, with the student names as the keys and their grades as the values.

We then iterate over the entries in the map using a for-each loop, and print the grades for each student to the console using the getKey() and getValue() methods of the Map.Entry interface.

The output of this program would be:

Alice: 90
Bob: 85
Charlie: 92
David: 87

Java LinkedHashMap Example:remove()

Sure, here’s an example of using the remove() method with a LinkedHashMap:

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a new LinkedHashMap to store user passwords
        Map<String, String> passwords = new LinkedHashMap<>();

        // Add some user passwords to the map
        passwords.put("Alice", "password123");
        passwords.put("Bob", "qwerty");
        passwords.put("Charlie", "abc123");
        passwords.put("David", "password456");

        // Print the passwords for each user
        for (Map.Entry<String, String> entry : passwords.entrySet()) {
            String user = entry.getKey();
            String password = entry.getValue();
            System.out.println(user + ": " + password);
        }

        // Remove a user from the map
        String removedPassword = passwords.remove("Charlie");
        System.out.println("Removed password: " + removedPassword);

        // Print the passwords again
        for (Map.Entry<String, String> entry : passwords.entrySet()) {
            String user = entry.getKey();
            String password = entry.getValue();
            System.out.println(user + ": " + password);
        }
    }
}

In this example, we create a new LinkedHashMap called passwords to store user passwords. We add some user passwords to the map using the put() method, with the user names as the keys and their passwords as the values.

We then iterate over the entries in the map using a for-each loop, and print the passwords for each user to the console using the getKey() and getValue() methods of the Map.Entry interface.

Next, we use the remove() method to remove the user “Charlie” from the map. We store the removed password in a variable called removedPassword, and print it to the console.

Finally, we iterate over the entries in the map again, and print the passwords for each user to the console. This time, the user “Charlie” should be missing from the output.

The output of this program would be:

Alice: password123
Bob: qwerty
Charlie: abc123
David: password456
Removed password: abc123
Alice: password123
Bob: qwerty
David: password456

Java LinkedHashMap Example: Book

Sure, here’s an example of using a LinkedHashMap to store information about books:

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Create a new LinkedHashMap to store information about books
        Map<String, Book> books = new LinkedHashMap<>();

        // Add some books to the map
        books.put("978-0596007126", new Book("Head First Java", "Kathy Sierra, Bert Bates", 2003));
        books.put("978-0132350884", new Book("Clean Code", "Robert C. Martin", 2008));
        books.put("978-0321356680", new Book("Effective Java", "Joshua Bloch", 2008));
        books.put("978-1449313876", new Book("Learning Python", "Mark Lutz", 2013));

        // Print the information about each book
        for (Map.Entry<String, Book> entry : books.entrySet()) {
            String isbn = entry.getKey();
            Book book = entry.getValue();
            System.out.println(isbn + ": " + book.getTitle() + " by " + book.getAuthor() + ", published in " + book.getYear());
        }
    }
}

class Book {
    private String title;
    private String author;
    private int year;

    public Book(String title, String author, int year) {
        this.title = title;
        this.author = author;
        this.year = year;
    }

    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }

    public int getYear() {
        return year;
    }
}

In this example, we create a new LinkedHashMap called books to store information about books. We add some books to the map using the put() method, with the ISBN numbers as the keys and Book objects as the values.

We then iterate over the entries in the map using a for-each loop, and print the information about each book to the console using the getKey() and getValue() methods of the Map.Entry interface, as well as the getTitle(), getAuthor(), and getYear() methods of the Book class.

The output of this program would be:

978-0596007126: Head First Java by Kathy Sierra, Bert Bates, published in 2003
978-0132350884: Clean Code by Robert C. Martin, published in 2008
978-0321356680: Effective Java by Joshua Bloch, published in 2008
978-1449313876: Learning Python by Mark Lutz, published in 2013