I’m having trouble with the more intricate map; for a standard Map<Long, String>, I would do something like:
Ordering<Long> valueComparator = Ordering.natural().onResultOf(Functions.forMap(myMap));
Map<Long, String> orderedMap = ImmutableSortedMap.copyOf(myMap, valueComparator);
But I can’t seem to get it to like Map<Long, Map<String, String>>, still ordered by Long. Maybe I’m missing something? Below doesn’t work…
Ordering<Long> valueComparator = Ordering.natural().onResultOf(Functions.forMap(myOtherMap));
Map<Long, Map<String, String>> orderedMyOtherMap = ImmutableSortedMap.copyOf(myOtherMap,valueComparator);
Your first example isn’t doing what you seem to be saying it’s doing. It’s creating a map that’s ordered by the
Stringvalues corresponding to eachLongkey. If you wanted to just order by the keys, you’d just do:The same thing would work for a
Map<Long, Map<String, String>>. The reason what you’re trying to do doesn’t work is that aMap<String, String>is notComparable, so there is no natural ordering for it.As an aside, you may want to consider using a
Table<Long, String, String>rather than aMap<Long, Map<String, String>>. There’s even a TreeBasedTable that will store the row and column keys in sorted order.