Java doesn't have a direct API to sort HashSet and LinkedHashSet collections. However, you can sort by converting them to TreeSet and ArrayList collections
Let's walk through this tutorial to explore in more details
Sort by converting to TreeSet
You can convert a HashSet or LinkedHashSet to TreeSet by using TreeSet constructors including TreeSet<>(Collection)
and TreeSet<>(Comparator)
If you use
TreeSet<>(Collection)
constructor to convert, the sorting logic will be based on theComparable
natural ordering of the underlying objectsIn the below example,
Comparable
is implemented inInteger
by default. ThedescendingSet()
method of aTreeSet
instance can also be used to get the reversed order from the defaultComparable
implementation
@Test
public void sortWith_TreeSet_And_Comparable() {
Set<Integer> set = new HashSet<>(Set.of(3, 1, 2));
NavigableSet<Integer> sortedSet = new TreeSet<>(set);
assertThat(sortedSet).containsExactly(1, 2, 3);
NavigableSet<Integer> descSet = sortedSet.descendingSet();
assertThat(descSet).containsExactly(3, 2, 1);
}
If you use
TreeSet<>(Comparator)
constructor in conjunction withaddAll(Collection)
method to convert, the sorting logic will be controlled by the givenComparator
The ordering can be inherited from the implemented
Comparable
of the underlying objects withComparator.naturalOrder()
or in the reverse order withComparator.reverseOrder()
@Test
public void sortWith_TreeSet_And_Comparator() {
Set<Integer> set = new HashSet<>(Set.of(3, 1, 2));
NavigableSet<Integer> sortedSet = new TreeSet<>(Comparator.reverseOrder());
sortedSet.addAll(set);
assertThat(sortedSet).containsExactly(3, 2, 1);
}
- A custom sorting logic can be specified to the
TreeSet<>(Comparator)
constructor withComparator.comparing(keyExtractor, keyComparator)
in whichkeyExtractor
is a function to extract the sort key from the underlying objects andkeyComparator
is used to compare the sort key
@Test
public void sortWith_TreeSet_And_CustomComparator() {
Book book1 = new Book(1, "b");
Book book2 = new Book(2, "c");
Book book3 = new Book(3, "c");
Set<Book> set = new HashSet<>(Set.of(book1, book2, book3));
Comparator<Book> c = Comparator
.comparing(Book::getTitle, Comparator.reverseOrder())
.thenComparing(Book::getId, Comparator.reverseOrder());
NavigableSet<Book> sortedSet = new TreeSet<>(c);
sortedSet.addAll(set);
assertThat(sortedSet).containsExactly(book3, book2, book1);
}
Book
is defined as the following
class Book {
int id;
String title;
Book(int id, String title) {
this.id = id;
this.title = title;
}
int getId() {
return id;
}
String getTitle() {
return title;
}
}
Sort by converting to ArrayList
You can convert a HashSet or LinkedHashSet to ArrayList by using ArrayList constructor ArrayList<>(Collection)
The created ArrayList is in the order returned by the given Set iterator. To sort it, you can use the
sort(Comparator.naturalOrder())
method to inherit the ordering logic defined by the implementedComparable
of the underlying objectsComparator.reverseOrder()
can also be used to get the reversed order from the default implementationIn the following example,
Comparable
is implemented inString
class by default to provide the alphabetical order
@Test
public void sortWith_ArrayList_And_Comparable() {
Set<String> set = new HashSet<>(Set.of("c", "a", "b"));
List<String> list = new ArrayList<>(set);
list.sort(Comparator.naturalOrder());
assertThat(list).containsExactly("a", "b", "c");
list.sort(Comparator.reverseOrder());
assertThat(list).containsExactly("c", "b", "a");
}
- A custom sorting logic can be specified to the
sort(Comparator)
method of aList
instance withComparator.comparing(keyExtractor, keyComparator)
as mentioned in the previous section
@Test
public void sortWith_ArrayList_And_CustomComparator() {
Book book1 = new Book(1, "b");
Book book2 = new Book(2, "c");
Book book3 = new Book(3, "c");
Set<Book> set = new HashSet<>(Set.of(book1, book2, book3));
List<Book> list = new ArrayList<>(set);
list.sort(Comparator
.comparing(Book::getTitle, Comparator.reverseOrder())
.thenComparing(Book::getId, Comparator.reverseOrder()));
assertThat(list).containsExactly(book3, book2, book1);
}
Learn more about sorting in ArrayList
Comparable and Comparator
In short, Comparable
and Comparator
provide the default and custom sorting logic, respectively, to the underlying objects in an array or collection
Learn more about Comparable and Comparator
Conclusion
In this tutorial, we learned sorting a HashSet or LinkedHashSet in Java by converting it to TreeSet or ArrayList. You can find below the full source code