Java LinkedHashMap Clear Remove All Example

This example shows how to clear LinkedHashMap in Java. This example also shows how to clear or how to remove all mappings from the LinkedHashMap using the clear method.

How to clear LinkedHashMap in Java?

The LinkedHashMap class maintains key-value pairs. There are a couple of ways using which you can clear the LinkedHashMap object.

1. Using the clear method

The clear method of the LinkedHashMap class removes all the mappings from the map object.

The LinkedHashMap object will be empty after this method call.

Output

2. By assigning a new object

You can also assign a new empty LinkedHashMap object to the same reference to make it empty.

Output

Which method should I use?

Both of these approaches work in a different manner. The clear method iterates the internal hash table and assigns a null to all the keys, thus making them eligible for garbage collection. The clear method does not change the capacity of the LinkedHashMap object, it remains the same.

When you assign a new object to the existing LinkedHashMap reference, the entire object including the key and value objects becomes eligible for the garbage collection (if they are not referenced anywhere else). In this case, the old object cannot be reused and it involves a costly operation of creating a new object.

If you are going to add a similar number of mappings to the LinkedHashMap object after clearing it, the clear method should perform better as it does change the capacity of the map plus it does not involve the creation of a new object. If not, and if the map contains a very large number of mappings, assigning a new object to the same reference will be ok.

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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *