How can I sort a HashSet in Java?
A HashSet is an unordered collection, so you cannot directly sort it. However, you can convert it to a List and sort the list using Collections. Sort. Example:
HashSet<Integer> set = new HashSet<>
set.add (3)
set.add (1)
set.add (2)
List<Integer> sorted List = new Array List<>(set)
Collections. Sort (sorted List)
Alternatively, you can use Java 8’s Stream API to sort the HashSet:
Set<String> hashSet = new HashSet<>
hashSet.add (“Orange”)
hashSet.add (“Apple”)
hashSet.add (“Banana”)
List<String> sortedList = hashSet.stream
.sorted .collect (Collectors.toList())
System.out.println(sortedList)
This will produce the same output as the previous example.
Note that if you need to maintain a sorted set, you may want to consider using a Tree Set instead of a HashSet. Tree Set is a sorted implementation of the Set interface.