When using TreeSet, any iterators associated with the keySet() or entrySet() should be in sorted order. Try this to
test:
Assuming you see the output in order, your TreeSet implementation is working fine. So the problem is probably elsewhere. Are you using a Comparator? Then check the code of the compare() method. Or if you're using Comparable keys, check the compareTo() code.
If you're using a preexisting Comparable class (like
String) be aware that "natural order" may not be exactly what you expect. For example numbers like "8", "9", "10", "11" are sorted alphabetically as "10, "11", "8", "9". If that's not what you want, you may need to make a Comparator to correct the problem.