HashSet
's iterator is not sorted because it just outputs the bins as-is. In fact, changing the implementation of the class, the load factor or any of the other parameters almost always changes the order of the iterator. However, you can wrap the set values in a List
and sort them using Collections.sort(List)
or Collections.sort(List, Comparator)
:
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
...
HashSet<? extends Comparable> myHashSet = ...;
...
List<? extends Comparable> sortedList = Arrays.asList(myHashSet.toArray(new Comparable[0]));
Collections.sort(sortedList);