Javatpoint Logo
Javatpoint Logo

Convert Set to Array in Java

In Java, Set and Array are two commonly used data structures. While a Set is an unordered collection of unique elements, an Array is a fixed-size, ordered collection of elements. There are scenarios where we might need to convert a Set to an Array in order to perform specific operations or meet certain requirements. In this section, we will explore various methods to achieve this conversion in Java.

Method 1: Using the toArray() Method

The simplest way to convert a Set to an Array is using the toArray() method provided by the Set interface. The method returns an array containing all the elements of the set.

Filename: SetToArrayExample.java

Output:

[banana, cherry, apple]

In this example, we first create a HashSet called set and add three elements to it. Then, we use the toArray() method to convert it to an array of strings.

Method 2: Using Java Streams

Another approach to converting a Set to an array is by using Java streams. The method provides more flexibility and allows for additional processing on the elements if needed.

Filename: SetToArrayExample.java

Output:

[20, 10, 30]

Method 3: Using Apache Commons Collections

If we are using the Apache Commons Collections library, we can use the org.apache.commons.collections4.SetUtils class to convert a Set to an array.

Filename: SetToArrayExample.java

Output:

[cat, bird, dog]

In this example, we first create a HashSet called set and add three elements. Then, we use the SetUtils.setToArray() method to convert it to an array of strings.

Conclusion

Converting a Set to an Array in Java is a common operation that can be accomplished using various methods. Depending on your specific requirements and preferences, you can choose the most suitable method for your application. Whether we opt for the toArray() method, Java streams, or utilize third-party libraries like Apache Commons Collections, you now have the knowledge to perform this conversion efficiently in your Java programs.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA