Skip to content

How to create LinkedHashMap in Java, LinkedHashMap Constructors

This example shows how to create a LinkedHashMap in Java. This example also shows how to create new LinkedHashMap using various constructors.

How to create new LinkedHashMap objects in Java?

The LinkedHashMap class in Java provides several constructors to create new objects of it.

How to create a new empty LinkedHashMap object?

The default constructor of the LinkedHashMap class creates a new empty map object with default capacity and load factor.

The default initial capacity of the LinkedHashMap in Java is 16 while the default load factor is 0.75.

How to create a new LinkedHashMap object with custom initial capacity and load factor?

If you want to create a map object with the custom initial capacity and default load factor, use the below given constructor.

Note: This LinkedHashMap constructor throws IllegalArgumentException exception if the specified initial capacity is negative.

If you want to specify both, the initial capacity and load factor, you can use the below given constructor.

Note: This LinkedHashMap constructor throws IllegalArgumentException exception if the specified initial capacity is negative or the specified load factor is not-positive value.

How to create a new LinkedHashMap object from another Map object?

The LinkedHashMap class provides a constructor that accepts a map object as an argument.

It creates a new linked hash map object with the same mapping as the specified map.

You can convert HashMap to LinkedHashMap using this constructor as given below.

Output

As you can see from the output, the linked hash map object has the same mapping as the specified hash map object.

Note: The above given constructor throws the NullPointerException exception if the specified map is null. Always check for null before using this constructor in your code.

You can also create a LinkedHashMap object from the TreeMap using this constructor as it accepts a Map object.

This example is a part of the Java LinkedHashMap tutorial with examples.

Please let me know your views in the comments section below.

References:
Java 8 LinkedHashMap

About the author

Leave a Reply

Your email address will not be published.