Java Creating a LinkedHashMap

Java Creating a LinkedHashMap

To create a LinkedHashMap in Java, you can use the LinkedHashMap class from the java.util package.

A LinkedHashMap is a map that maintains the insertion order of its elements. It is similar to a HashMap, but it also maintains a doubly-linked list running through all of its entries. This allows the elements to be ordered based on when they were added to the map.

Here is an example of how to create an empty LinkedHashMap:

import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
    }
}
Sour‮w:ec‬ww.lautturi.com

This creates a LinkedHashMap that maps strings to integers. You can also specify the key and value types using the generic syntax LinkedHashMap<KeyType, ValueType>.

To add elements to the map, you can use the put method. For example:

map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);

This adds the key-value pairs ("apple", 1), ("banana", 2), and ("cherry", 3) to the map.

You can also create a LinkedHashMap and add elements to it in one step using the putAll method. For example:

import java.util.LinkedHashMap;
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("apple", 1);
        map1.put("banana", 2);
        map1.put("cherry", 3);
        
        LinkedHashMap<String, Integer> map2 = new LinkedHashMap<>();
        map2.putAll(map1);
    }
}

This creates a LinkedHashMap and adds all of the key-value pairs from map1 to it.

Created Time:2017-11-03 00:14:39  Author:lautturi