Print TreeSet in Java Example (Print Elements)

This example shows how to print TreeSet in Java. The example also shows how to print all elements (display all elements) of the TreeSet of custom class objects.

How to print TreeSet elements in Java?

There are several ways using which we can print TreeSet elements or display TreeSet elements as given below.

1. Using the enhanced for loop

We can use the enhanced for loop to iterate over the TreeSet and print the elements one by one as given below.

Output

2. Using the forEach (Java 8)

If you are using Java version 8 or later, you can use the forEach instead of the enhanced for loop as given below.

Output

3. Using the Iterator

We can also the TreeSet Iterator as given below.

Output

4. Using the Arrays class

The Arrays class provides the toString method to display the array. But before we can use that, we need to convert TreeSet to an array as given below.

Output

Note: Converting TreeSet to an array just for the display purpose is not recommended especially if the TreeSet is large. It may not perform well as allocating a new array with TreeSet elements is a costly operation in terms of performance.

How to print elements of TreeSet having custom class objects?

When we try to print a TreeSet of a custom class, the console does not display the useful information. Let’s see an example of that.

Output

As we can see from the output, the information printed on the console is not useful at all. That is because whenever we print the object, its toString method is called.

Since the User class has not overridden it, the toString method inherited from the Object class is used that prints object information in “[email protected]_code” format.

If we want to return useful information whenever the object is printed, we need to override the toString method in the class. Let’s do that and try again.

Output

As we can see from the output, the toString method is called each time the object is printed in the console.

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

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

References:
Java 8 TreeSet

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 *

Online Shopping