1

I have a TreeSet.

The string key is actually a string value of an int, as freemarker doesn't allow ints as keys to maps, and as this is a sorted map, it sorts it as below:

1
10
11
12
2
3
4
5
6
7
8
9

Anyone know how to get around this and make it print in numerical order?

Thanks

Ben Taliadoros
  • 7,003
  • 15
  • 60
  • 97

2 Answers2

2

Construct the map with an appropriate comparator via the constructor TreeMap(Comparator).

(Or TreeSet, if that's what you actually mean; you mention both sets and maps.)

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
2

String internally imposes a lexicographic order via compareTo.

Compares two strings lexicographically.

If you don't want that, consider specifying a custom Comparator e.g.

final Map<String, ...> map = new TreeMap<String, ...>(new Comparator<String>() {

  public int compare(final String a, final String b) {
    return Integer.valueOf(a).compareTo(Integer.valueOf(b));
  }
});
obataku
  • 29,212
  • 3
  • 44
  • 57