Skip to content

Convert TreeSet to Array in Java Example

This example shows how to convert a TreeSet to an array in Java. This example also shows how to convert a TreeSet object to an array using the toArray method and Java 8 stream.

How to convert a TreeSet object to an array in Java?

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

1. Using the toArray method of the TreeSet class

The toArray method of the TreeSet class returns a new array containing all the elements of the TreeSet object.

The array returned by the toArray method has elements in the order that is returned by the iterator of the TreeSet object. For a TreeSet object, that is the natural ordering of the elements (defined by the Comparable interface) or the order defined by the custom comparator.

Output

As we can see from the output, the elements of the array are sorted in the natural order of the TreeSet elements i..e ascending order for the Integer type.

Important Note:

If the array specified in the toArray method is large enough to fit all the TreeSet elements, the same array is filled with the TreeSet elements and returned. If the specified array is bigger than the size of the TreeSet, the array element that immediately comes after the TreeSet elements is set to null.

Output

As we can see from the output, the array element “6” is set to null to mark the end of the TreeSet elements and the rest of the array elements are kept as is.

If the specified array is smaller than the TreeSet size, the toArray method allocates a new array of the same size, fills it with the TreeSet elements and returns it. Always pass the array of the same size as that of the TreeSet object to avoid the costly operation of allocating a new array.

2. Using Java 8 stream

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

Output

Please also visit how to convert an array to TreeSet example to know more.

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

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

References:
Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.