Skip to content

Java Print HashSet Example (Display HashSet)

This example shows how to print HashSet in Java. This example also shows how to print HashSet elements using for loop, Arrays class, and Java stream.

How to print HashSet elements in Java?

There are several ways using which we can print HashSet elements or display HashSet elements in the console as given below.

1. Using the for loop

We can use the enhanced for loop to iterate over HashSet object and display the elements one by one.

Output

2. Using the Iterator

Instead of using the for loop, we can also use the Iterator as given below.

Output

3. Using the Arrays class

We can convert the HashSet to an array and then use the toString method of the Arrays class to display the array as given below.

Output

If you do not want the opening and closing square brackets, you can remove them by using the regular expression along with the String replaceAll method as given below.

Output

4. Using forEach (Java 8)

If you are using Java version 8 or later, you can use the forEach method to print the HashSet elements.

Output

How to print HashSet of custom class objects?

Let’s see what happens when we try to print HashSet of custom class objects using the enhanced for loop.

Output

Since the Order custom class has not overridden the toString method, the toString method inherited from the Object class is used when we print the element. The toString method of the Object class returns a string containing the object information in “class_name@object_hashcode” format that is not useful to read.

If we want to print useful information, we need to override the toString method in the Order class as given below.

Output

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

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

References:
Java 8 HashSet

About the author

Leave a Reply

Your email address will not be published.