Learn different ways of Sorting the elements of a Java HashSet.
Tutorial Contents
Overview
Java HashSet, an implementation of the Set interface, is an unordered and unsorted collection of unique elements. That means it doesn’t guarantee the order of the elements.
This tutorial demonstrates ways of sorting Java HashSet elements with the help of examples.
Using TreeSet
A Java TreeSet collection that implements the Set interface is a unique collection of sorted elements. This means when we add elements to a TreeSet, it stores them in a sorted manner.
To sort a HashMap instance using a TreeSet, we can create a TreeSet instance and dump all the HashMap elements into it.
Set<Integer> hashSet = Set.of(3, 2, 5, 4, 1, 6, 8, 7);
Set<Integer> treeSet = new TreeSet<>(hashSet);
System.out.println(treeSet);
//prints:
//[1, 2, 3, 4, 5, 6, 7, 8]
Code language: Java (java)
The TreeSet constructor creates a new TreeSet instance containing all the elements from the given Collection.
Using Collections sort() Method
The Collections class in Java provides a few valuable abstractions and utility methods. The sort() method sorts the given List implementations.
To sort a HashMap using the Collections.sort() method, we need to convert our HashSet to an ArrayList.
Set<Integer> set = Set.of(3, 2, 5, 4, 1, 6, 8, 7);
List<Integer> list = new ArrayList<>(set);
Collections.sort(list);
System.out.println(list);
//prints:
//[1, 2, 3, 4, 5, 6, 7, 8]
Code language: Java (java)
The ArrayList constructor creates a new ArrayList containing all the elements from the given Collection, a HashSet in our case.
Using Stream sorted() method
The Java Stream API supports several Intermediate Operations that are useful for processing and manipulating Stream elements. The sorted() method of the Java Stream returns a new Stream containing sorted elements from this Stream.
We can use the Stream sorted() method to sort a Java HashSet.
Set<Integer> hashSet = Set.of(3, 2, 5, 4, 1, 6, 8, 7);
Set<Integer> linkedHashSet = hashSet.stream()
.sorted()
.collect(Collectors.toCollection(LinkedHashSet::new));
System.out.println(linkedHashSet);
//prints:
//[1, 2, 3, 4, 5, 6, 7, 8]
Code language: Java (java)
Please note that we use the empty sorted() method to sort the elements in their natural order. After the sorting, we collect the sorted elements in a LinkedHashSet. That is because the LinkedHashSet is an ordered implementation of the Set interface; thus, it maintains the order of the sorted elements.
Summary
This quick tutorial provided examples of Sorting a HashSet in Java. Java HashSet instances are unordered collections; thus, we need to sort them by converting them to other closest types. We studied the examples of using a TreeSet, the Collections.sort() method, and the Stream.sorted() method to sort Java HashSet instances.
Please refer to our GitHub Repository for the complete source code.