The following two methods are described:
Method 1: convert the HashSet to List and use Collections. sort () for sorting.
Method 2: convert a Hashset to a TreeSet
The following code provides two methods:
| The code is as follows: |
Copy code |
|
Public class HashSetSortingDemo {
Public static void main (String args []) {
HashSet <String> names = new HashSet <String> ();
Names. add ("Asker ");
Names. add ("Crak ");
Names. add ("Bayliss ");
Names. add ("Mohna ");
Names. add ("Dina ");
System. out. println ("HashSet before sorting:" + names );
// Convert the HashSet to List and use Collections. sort () for sorting
List <String> tempList = new ArrayList <String> (names );
Collections. sort (tempList );
System. out. println ("HashSet element in sorted order:" + tempList );
// Use TreeSet to sort HashSet
TreeSet <String> sorted = new TreeSet <String> (names );
System. out. println ("HashSet sorted using TreeSet:" + sorted );
}
} |
There is just a problem. Since we want to sort data, why didn't we need to sort hashset?