HashSet are unsorted collections. Sorting of HashSet can be done in multiple ways.
In this post we will see examples on sorting of HashSet using ArrayList and TreeSet.
Example: Sorting of HashSet in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package com.kscodes.sampleproject; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.TreeSet; public class HashSetSorting { public static void main(String[] args) { HashSet<String> hashSet = new HashSet<>(); hashSet.add("Windows"); hashSet.add("Apple"); hashSet.add("Andriod"); hashSet.add("Linux"); hashSet.add("Unix"); System.out.println("****HashSet Element - UnSorted"); for (String element : hashSet) { System.out.println(element); } // Convert the hashSet to ArrayList and then use Collections.sort List<String> arrayList = new ArrayList<>(hashSet); Collections.sort(arrayList); System.out.println("****Sorted Elements - Using ArrayList"); for (String element : arrayList) { System.out.println(element); } // Convert the hashSet to TreeSet which // will automatically sort the HashSet TreeSet<String> treeSet = new TreeSet<>(hashSet); System.out.println("****Sorted Elements - Using TreeSet"); for (String element : treeSet) { System.out.println(element); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
****HashSet Element - UnSorted Linux Windows Unix Apple Andriod ****Sorted Elements - Using ArrayList Andriod Apple Linux Unix Windows ****Sorted Elements - Using TreeSet Andriod Apple Linux Unix Windows |