Convert LinkedHashMap to Two Arrays Example

This example shows how to convert LinkedHashMap to two arrays in Java such that the one array contains all the keys of the LinkedHashMap and another all values.

How to convert LinkedHashMap to two arrays in Java?

The LinkedHashMap class maps keys to values while the array in Java is a collection of the same type of elements. However, you can put all the keys of HashMap in one array and all the values in an another array.

To get all the keys of the LinkedHashMap, you can use the keySet method.

This method returns a Set view of all the keys contained in the LinkedHashMap object. Once you get all the keys in a Set, use the toArray method of the Arrays class to convert it to an array.

Similarly, you can use the values method of the LinkedHashMap class to get all the values contained in the map.

This method returns a Collection view of all the values stored in the LinkedHashMap object. Once you get all the values in a Collection, use the toArray method of the Arrays class to convert Collection to an array.

The below given example shows how to convert the key set and value collection to two arrays.

Output

Important Note:

Always make sure to pass the array of the same size as that of Set or a Collection to the toArray method. The toArray method returns the same array if it is large enough to contain all the elements of the Set or a Collection. If not, it allocates a new array, fills it with elements and returns it.

Since an array allocation is a costly operation in terms of performance, it is a good practice to pass the array of the required length to the toArray method.

This example is a part of the LinkedHashMap in Java Tutorial.

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 *