How to Print LinkedHashSet Elements in Java?
LinkedHashSet is a child class of HashSet in which duplicates are not allowed but the insertion order is preserved. The elements are printed in the same order in which they were inserted.
There are several ways to print LinkedHashSet elements:
- By simply printing the elements
- By using enhanced for loop
- Using iterator
- Using Arrays.toString()
- Printing elements of LinkedHashSet having objects of custom class using .toString() method of Object Class.
Method 1: Simply Printing the elements to console
- We’ll first make an instance of the LinkedHashSet ,add the elements in it and simply print it to the console.
- One method is to simply print the Collection object name and the contents of the LinkedHashSet will be printed.
[Hey, How, are, You]
Method 2: Using Enchanced for loop
We can simply print the elements using the enhanced for loop concept or for-each loop concept by iterating over all the LinkedHashSet elements.
To print the elements using for-each loop follow the following steps:-
- Set up a for-each loop by declaring a variable of the same type as the base type of Collection class i.e. of the same type as the elements of LinkedHashSet, followed by a colon, which is then followed by the object name.
- Inside the loop, simply print the variable name to display all the contents.
1 5 3 9
Method 3: By using an Iterator
We can use an iterator over LinkedHashSet elements using the iterator method and print them using next() and hasNext() methods.
To cycle through the contents of the LinkedhashSet following steps will be followed:-
- Obtain an iterator to start by calling an Iterator method.
- Set up a loop that calls hasNext() and iterate until hasNext() return true.
- Inside the loop, print each element using next().
Alok Ayush Abhinav Akash Atul
Method 4: Using Array.toString()
To use it we first need to convert the LinkedHashSet to an array and then use the .toString() method to print them.
- Convert the contents of the LinkedHashSet to an Array using .toArray method.
- Now convert the arrays elements to their String representation using Arrays.toString() and print them.
[678, 789, 876, 589]
Method 5: Printing elements of LinkedHashSet having objects of custom class
- We can print the contents of the custom class simply by the below approach but there is a key thing that needs to be kept in mind before printing it.
- Whenever an object is printed its .toString() method is called to get its String representation, if the custom class has not overridden the method then it is inherited from the Object class.
- The toString() of the Object class prints the contents of the object as “ClassName@ObjectHashCode”, this would not be our requirement, so we override the toString() in the custom class so that only the information that we require will be printed.