[英]How to sort the values of a HashMap freemarker template
I have in java this HashMap: 我在java中有这个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: 我在这种模式下使用freemarker模板打印:
<#list 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? 如何使用freemarker模板对值进行排序?
Try this: 尝试这个:
<#list map?values?sort as v>
${v} -
</#list>
Notice the use of the sort
builtin for the sequence of values. 注意对值序列使用了内置
sort
。
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. 如果要显示独立于键的值,则可以从地图中取出值并从中构造TreeSet。 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. 由于未对HashMaps进行排序,因此可以预测此行为。 As has been pointed out in the comments a SortedMap eg TreeMap will sort on the keys.
正如在评论中指出的那样,SortedMap例如TreeMap将对键进行排序。 So you're going to have to cut some code to sort this.
因此,您将不得不削减一些代码来对此进行排序。
See Sort a Map<Key, Value> by values (Java) 请参阅按值排序地图<键,值>(Java)
HashMap is not ordered. HashMap没有订购。 You should use a TreeMap instead which implements a SortedMap :-
您应该使用TreeMap来实现SortedMap : -
SortedMap<String, String> map = new TreeMap<String, String>();
Please note - Sorted Map provides a total ordering on its keys
. 请注意 -
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 .
如果要对值进行排序,可以通过使用Comparable对Map.entrySet()进行排序来始终对其进行排序。
Also take a look at this very similar question: TreeMap sort by value 另请看一下这个非常相似的问题: TreeMap按值排序
如果需要以可预测的顺序迭代HashMap
,则可以使用具有可预测迭代顺序的LinkedHashMap ,它维护一个运行所有条目的双向链表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.