How to sort the values of a HashMap freemarker template
I have in java this HashMap:
HashMap<String, String> map = new HashMap<String, String>();
map.put("k1", "3");
map.put("k2", "4");
map.put("k3", "2");
map.put("k4", "6");
map.put("k5", "1");
map.put("k6", "5");
I print with freemarker template in this mode:
<#lis开发者_Python百科t map?values as v>
${v} -
</#list>
but it prints in this order:
2 - 6 - 1 - 5 - 3 - 4
I would like to print in this order:
1 - 2 - 3 - 4 - 5 -6
how can I sort values with with freemarker template?
Try this:
<#list map?values?sort as v>
${v} -
</#list>
Notice the use of the sort
builtin for the sequence of values.
If you are displaying the values independent of the keys then you can take the values out of the map and construct a TreeSet from it. Then the values would be in order.
TreeSet ordered = new TreeSet(map.values());
Then
<#list ordered as v>
${v} -
</#list>
This behaviour is predictable as HashMaps are not ordered. As has been pointed out in the comments a SortedMap e.g. TreeMap will sort on the keys. So you're going to have to cut some code to sort this.
See Sort a Map<Key, Value> by values (Java)
HashMap is not ordered. You should use a TreeMap instead which implements a SortedMap:-
SortedMap<String, String> map = new TreeMap<String, String>();
Please note - Sorted Map provides a total ordering on its keys
. You cannot have it sorted on the values. If you want to sort on values you can always do that by sorting on the Map.entrySet() using a Comparable .
Also take a look at this very similar question: TreeMap sort by value
If you need iteration over a HashMap
in predictable order, you can use a LinkedHashMap with predictable iteration order, it maintains a doubly-linked list running through all of its entries.
精彩评论