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 theComparablenatural ordering of the underlying objectsIn the below example,
Comparableis implemented inIntegerby default. ThedescendingSet()method of aTreeSetinstance can also be used to get the reversed order from the defaultComparableimplementation
@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 givenComparatorThe ordering can be inherited from the implemented
Comparableof 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 whichkeyExtractoris a function to extract the sort key from the underlying objects andkeyComparatoris 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 implementedComparableof the underlying objectsComparator.reverseOrder()can also be used to get the reversed order from the default implementationIn the following example,
Comparableis implemented inStringclass 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 aListinstance 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