Convert LinkedHashSet to Array in Java Example

This example shows how to convert LinkedHashSet to an array in Java. This example also shows how to convert LinkedHashSet to an array using the toArray method and Java 8 Stream.

How to convert LinkedHashSet to an array in Java?

There are a couple of ways using which we can convert LinkedHashSet object to an array as given below.

1. Using the toArray method

We can use the toArray method of the LinkedHashSet class to convert to an array.

The toArray method returns an array containing all the elements of this linked hash set object. Since the LinkedHashSet iterator guarantees the element order, the order of the array elements is the same as the insertion order in the LinkedHashSet.


Important Note:

If the array specified in the toArray method is large enough to hold all elements of the LinkedHashSet object, the same array is filled with the elements and returned. If the specified array is smaller than the linked hash set object, a new array is allocated, filled with the set elements and then returned.

Always make sure that the array is at least equal to the size of the LinkedHashSet object to avoid the costly operation of a new array allocation.

If the specified array is bigger than the linked hash set object, the element that comes immediately after the linked hash set elements is set to null to indicate the end of the set elements as shown below.


As we can see from the output, the array element located at the index 3 (i.e. 4th element “white”) is set to null to indicate the end of the set elements. However, do not rely on this null value to determine the end of the elements as the LinkedHashSet object itself might contain a null value.

2. Using Java 8 Stream

If you are using Java version 8 or later, you can use the Java 8 stream to convert LinkedHashSet to the array of the same type as given below.


This example is a part of the LinkedHashSet in Java Tutorial with Examples.

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

Java 8 LinkedHashSet

About the author



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 *

Online Shopping