Convert Array to LinkedHashSet in Java Example

This example shows how to convert an array to LinkedHashSet in Java. This example also shows how to convert array to LinkedHashSet using constructor, addAll method, Java 8 Stream, and Apache Commons library.

How to convert an array to LinkedHashSet in Java?

There are several ways using which we can convert an array to an object of the LinkedHashSet in Java as given below.

1. Using the asList method and LinkedHashSet constructor

The LinkedHashSet class provides a constructor that accepts a collection object. But before we can use that, we need to convert array to a List using the asList method of the Arrays class.

Output

2. Using the asList method and addAll method

Similar to the above given approach, we will first convert an array to a List and then add all elements of the List to the linked hash set object using the addAll method.

Output

3. Using the addAll method of the Collections class

Instead of using the addAll method of the LinkedHashSet class, we can also use the addAll method of the Collections class as given below.

We do not need an additional step of converting the array to a List using this approach, as the addAll method directly accepts an array.

4. Using Apache Commons Library

If you are using the Apache Commons library in your project, you can use the addAll method of the CollectionUtils class as given below.

Output

5. Using a loop

We can iterate through elements of the array using a for loop or enhanced for loop and add elements to LinkedHashSet object one by one as given below.

Output

6. Using Java 8 stream

If you are using Java version 8 or later, you can also use the stream to convert an array to a Set 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

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 *