Skip to content

How to Print LinkedHashSet Elements in Java Example

This example shows how to print LinkedHashSet elements (display LinkedHashSet) in Java. This example also shows how to print LinkedHashSet in the console using for loop, Arrays class, forEach, and Java Stream.

How to print LinkedHashSet elements in Java?

There are several ways using which we can print LinkedHashSet elements in the console or a log file as given below.

1. Using the enhanced for loop

We can use the enhanced for loop to iterate LinkedHashSet elements and print them.

Output

2. Using the Iterator

We can get an iterator over LinkedHashSet elements using the iterator method and then iterate and print the elements using the hasNext and next methods as given below.

Output

3. Using the forEach method

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

Output

4. Using the toString method of the Arrays class

In order to use the toString method of the Arrays class, we first need to convert LinkedHashSet to an array. Once converted, the toString method can be used to display the LinkedHashSet elements.

Output

If you want to remove the square brackets and spaces from between the elements, you can use the “[\\[\\]\\s]” regular expression pattern along with the String replaceAll method.

Output

How to print LinkedHashSet having objects of a custom class?

When any object is printed, its toString method is called to get the string representation. If the custom class has not overridden it, the toString method inherited from the Object class is called.

The toString method of the Object class prints the object information in “ClassName@ObjectHashCode” format.

Output

As we can see from the output, the object information is not very useful. We can solve this by implementing the toString method in the Student custom class as given below.

Output

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

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

References:
Java 8 LinkedHashSet

About the author

Leave a Reply

Your email address will not be published.