Introduction
In this lab, we will be learning how to sort the elements of a HashSet in Java. Java provides various methods and techniques to sort HashSet elements that we will be discussing in this lab.
Create a Java file
Create a Java file named SortHashSet.java in the ~/project directory using the following command:
touch ~/project/SortHashSet.java
Import HashSet, Set and TreeSet Classes
Import java.util.HashSet, java.util.Set, and java.util.TreeSet classes in the SortHashSet.java file using the following code:
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
Create a HashSet and Add Elements
Create a HashSet and add some elements to it using the following code:
Set<Integer> hashSet = new HashSet<>();
hashSet.add(10);
hashSet.add(30);
hashSet.add(20);
hashSet.add(40);
System.out.println("HashSet elements: " + hashSet);
Sort HashSet using TreeSet
Sort the HashSet in ascending order using the TreeSet class and display it using the following code:
Set<Integer> treeSet = new TreeSet<>(hashSet);
System.out.println("Sorted HashSet elements (Ascending Order): " + treeSet);
Sort HashSet using ArrayList and Collections.sort() Method
Sort the HashSet using ArrayList and the Collections.sort() method and display it using the following code:
List<Integer> arrayList = new ArrayList<>(hashSet);
Collections.sort(arrayList);
System.out.println("Sorted HashSet elements using Collections.sort(): " + arrayList);
Sort HashSet using Stream API
Sort the HashSet using Stream API and display it using the following code:
List<Integer> streamList = hashSet.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted HashSet elements using Stream API: " + streamList);
Compile and Run the Java file
Compile and run the SortHashSet.java file using the following commands:
javac SortHashSet.java
java SortHashSet
Modify the elements of the HashSet
Modify the elements of the HashSet in the SortHashSet.java file using the following code:
hashSet.add(50);
hashSet.add(70);
hashSet.add(60);
System.out.println("Modified HashSet elements: " + hashSet);
Compile and Run the Java file Again
Compile and run the SortHashSet.java file again using the following commands:
javac SortHashSet.java
java SortHashSet
Summary
In this lab, we learned how to sort HashSet elements in Java using TreeSet, ArrayList and Collections.sort() method, and Stream API. HashSet is an implementation class of the Set interface in Java that is used to store data but does not maintain any order. Java provides TreeSet to store sorted data. We also learned how to modify the HashSet elements and verify the output of the Java program.



