Java

Java Sort Set

The interface of Java Set extends the Collection interface. The elements of a Java Set do not follow any specific order, unlike those of a List. A limitation over the point where an element can be inserted is NOT provided by Java Set. Searching for elements in the set and accessing them by their index at the same time is not possible in the Java set. The iterator for the set cycles through the set-in ascending order. The Java set has various additional procedures to properly utilize the sorting. The Comparable interface must be defined by every element that is given to a sorted set.

Example 1:

The program is to create and display the sorted set. The following HashSet is used to make the set and then sort that set via the TreeSet method:

import java.util.*; public class SortSet1 {
public static void main(String args[]) {
int arr[] = {76, 13, 46, 6, 89, 102, 25, 76, 59, 19};
Set set = new HashSet();
try {
   for (int i = 0; i< 5; i++) {
set.add(arr[i]);
}
System.out.println(set);
TreeSet sort = new TreeSet(set);
System.out.println("Sorted Set = ");
System.out.println(sort);
catch (Exception e) {}
  }
}

We implement the sort set code inside the main() method of the “SortSet1” Java class. Then, we declare an array of integers in the “arr[]” variable. After this, we create the set using the HashSet() class in a “set” variable. Next, we have a try block to get the elements from the array using the for-loop method. The for-loop method cycles over the elements of the array until the index “5” is reached. Once the element of the array is obtained, we add it to the HashSet “set” object by calling the add() method.

Since the set is created with unorganized values, the values are then sorted with the help of TreeSet. We declare the “sort” variable for the TreeSet class and input the HashSet “Set” variable as a parameter. The TreeSet sorts the set values in ascending order by default which is printed via the println() method.

The first five elements from the array are added to the set which is displayed on the following screen. After that, the sorted set of values from the TreeSet interface is also displayed:

Example 2:

The stream() method provides a quick solution to sort the set in Java. It uses pipeline methods to display the objects from various collections in the desired order. Then, sort the final sequence before displaying it using the sorted() method.

import java.util.*;
public class SortSet2 {
public static void main(String[] args) {
HashSetMySet = new HashSet();
MySet.add(50);
MySet.add(43);
MySet.add(49);
System.out.println("Unsorted: ");
MySet.forEach (System.out::println);
System.out.println("Sorted: ");
MySet.stream().sorted().forEach(System.out::println);
  }
}

The main() method is specified in the “SortSet2” Java class where the sorting is accomplished using the stream() method. First, we create the set using the HashSet interface in the “MySet” variable. After that, the set is added with the three unorganized numerical values. The unsorted values of a set are printed before the sorting operation. Then, we call the “MySet” variable along with the stream() method to generate the sequential stream which is then sorted from the sorted() method. The sorted set of streams is traversed by the foreach method and prints those sorted set values on the output screen.

The following prompt screen displays a stream of ordered set values:

Example 3:

The order of the elements in a hash set is not maintained. As a result, HashSet cannot be sorted. Indirect sorting of the HashSet’s elements is possible by converting it to a List or TreeSet. However, the values remain in their objective type rather than the HashSet type.

import java.util.*;
public class SortSet3 {
public static void main(String args[]){
HashSetstrSet = new HashSet();
strSet.add("Hello");
strSet.add("people");
strSet.add("Good");
strSet.add("Morning");
System.out.println("Unsorted HashSet: "+ strSet);
TreeSetstrTreeSet = new TreeSet(strSet);
System.out.println("HashSet elements in sorted order :" + strTreeSet);
 }
}

The previous “SortSet3” Java class contains a main() method block for providing the source code of sorting a set. We give an interface of the HashSet class where the HashSet() is employed in the “strSet” variable. The HashSet() is used to create the empty set which is then added to the strings by employing the add() method. The set is initially unsorted which we sort by setting the interface of the TreeSet. We initialize the TreeSet() in the “strTreeSet” variable and pass the “StrSet” variable of the HashSet. The TreeSet organizes the sequence of the string values of the specified set and prints them.

The random string set is first generated which is not organized. The sorted strings are the set which are displayed after that which is obtained from the TreeSet class.

Example 4:

There is a SortedSet interface which is used to include the functionality that allows all of its elements to be stored in sorted order. The first and the lowest value from the provided set is returned by the SortedSet interface’s first()method.

import java.util.SortedSet;
import java.util.TreeSet;
public class SortSet4 {
public static void main(String[] args) {
SortedSet s = new TreeSet();
s.add("j");
s.add("a");
s.add("v");
s.add("a");
System.out.println("Set Values: ");
for (Object obj: s) {
System.out.println(obj);
  }
System.out.println("Set First Value: + s.first());
}
}

The “SortSet4” class is constructed which has the main() method for sorting the operation. We provide the sortedSet class object “s” which has the TreeSet to generate the set. After this, we insert some string characters inside the newly created TreeSet with the add() method. This sorts the set and doesn’t show the repeated values. The TreeSet with the string characters is then displayed by iterating through the foreach method. Then, we have the deployment of the first() method to get the first element of the set which is obtained after the sorting operation.

The output of the sorted set is obtained from the TreeSet class. Furthermore, the first value from the TreeSet id is also fetched from the first() method.

Example 5:

The Java SortedSet interface’s comparator() method is implemented to give the comparator that is used to arrange the elements of the specified set. Additionally, if the specified set uses the element’s natural ordering, the method provides a null value.

import java.util.SortedSet;
import java.util.TreeSet;
public class SortSet5{
public static void main(String[] args) {
SortedSetSetValues = new TreeSet();
SetValues.add("London");
SetValues.add("Bristol");
SetValues.add("Manchester");
SetValues.add("Leed");
System.out.println("The set elements: ");
for (Object x:SetValues) {
}
System.out.println(x);
System.out.println("The set comparator: + SetValues.comparator());
}
}

The “SortSet5” Java class is employed with the main() method inside it. Here, we declare a “SetValues” variable to set the TreeSet to get the ordered set of values. The set is filled by inserting the string items in the add() method. After that, we have a foreach method to get the sorted set and print that sorted set on the screen. After that, we invoke the comparator() method on the TreeSet “SetValues” which generates the null value as we used the TreeSet. The TreeSet sorts the set by default.

The set of TreeSet elements is organized in a sorted order which is why we get the null from the comparator() method of the sortedSet class.

Conclusion

A set is performed to establish a certain ordering of its elements. The items are arranged using a natural sorting method. We implemented the set with the different interfaces in the provided source programs. We first created and accessed its values. Then, we used the TreeSet method to simply sort the set. In the last source programs, the sortedSet interface is applied with its different methods to sort the sets.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.