Search code examples
javaspringhashmapfreemarkertreeset

How to overcome freemarker treeset sorting int keys alphabetically?


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


Solution

  • 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));
      }
    });