Given a HashSet in Java, the task is to sort this HashSet.
Input: HashSet: [Geeks, For, ForGeeks, GeeksforGeeks] Output: [For, ForGeeks, Geeks, GeeksforGeeks] Input: HashSet: [2, 5, 3, 1, 4] Output: [1, 2, 3, 4, 5]
The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means that the class does not guarantee the constant order of elements over time.
It means that HashSet does not maintains the order of its elements. Hence sorting of HashSet is not possible.
However, the elements of the HashSet can be sorted indirectly by converting into List or TreeSet, but this will keep the elements in the target type instead of HashSet type.
Below is the implementation of the above approach:
Program 1: By Converting HashSet to List.
Original HashSet: [practice, geeks, contribute, ide] HashSet elements in sorted order using List: [contribute, geeks, ide, practice]
Program 2: By Converting HashSet to TreeSet.
Original HashSet: [practice, geeks, contribute, ide] HashSet elements in sorted order using TreeSet: [contribute, geeks, ide, practice]
- HashSet in Java
- HashSet add() Method in Java
- Initializing HashSet in Java
- HashSet contains() Method in Java
- HashSet vs TreeSet in Java
- Traverse through a HashSet in Java
- HashSet isEmpty() Method in Java
- HashSet retainAll() method in Java with Example
- HashSet equals() method in Java with Example
- Convert HashSet to TreeSet in Java
- Internal working of Set/HashSet in Java
- HashSet clear() Method in Java
- HashSet iterator() Method in Java
- Difference between ArrayList and HashSet in Java
- HashSet clone() Method in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.