Skip to content

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.

Output

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.

Output

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.

Output

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

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

References:
Java 8 LinkedHashSet

About the author

Leave a Reply

Your email address will not be published.