Junior — Middle
How can elements in a HashSet be ordered?
sobes.tech AI
Answer from AI
HashSet in Java does not guarantee the order of elements because it is based on a hash table. To order elements from a HashSet, you can:
- Convert the HashSet to a List, and then sort it using Collections.sort() or the Stream API.
HashSet<String> set = new HashSet<>();
set.add("banana");
set.add("apple");
set.add("orange");
List<String> list = new ArrayList<>(set);
Collections.sort(list);
for (String fruit : list) {
System.out.println(fruit);
}
- Use a TreeSet, which stores elements in sorted order if order is important from the start.
TreeSet<String> sortedSet = new TreeSet<>(set);
for (String fruit : sortedSet) {
System.out.println(fruit);
}
Thus, ordering is achieved either by sorting after extraction or by using a data structure that maintains order.