这个例子将展示如何在groovy中按值对Map或Dictionary进行排序。如果你有一个域,一个键和值的表,你可能想用描述的顺序来显示一个下拉菜单。如果你不能通过数据库排序,一个直接的方法是按值对Map进行排序。我从gmail中提取了一些用于邮件操作的样本值。
我们将使用groovy spaceship operator。对于按值反向排序的map,我们只需切换我们要比较的内容。
@Test
void sort_map_by_value() {
def myMap = [1:"More", 2:"Mark as read", 3: "Mark as important", 4:"Add to tasks"]
assert [
"Add to tasks",
"Mark as important",
"Mark as read",
"More"] == myMap.sort({a, b -> a.value <=> b.value})*.value
}
@Test
void sort_map_by_value_reverse() {
def myMap = [1:"More", 2:"Mark as read", 3: "Mark as important", 4:"Add to tasks"]
assert [
"More",
"Mark as read",
"Mark as important",
"Add to tasks"] == myMap.sort({a, b -> b.value <=> a.value})*.value
}
@Test
void sort_map_by_value_case_insensitive() {
def myMap = [1:"More", 2:"Mark as read", 3: "Mark as important", 4:"Add to tasks"]
assert [
"Add to tasks",
"Mark as important",
"Mark as read",
"More"] == myMap.sort({a, b -> a.value.toLowerCase() <=> b.value.toLowerCase()})*.value
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : http://www.leveluplunch.com/groovy/examples/sort-map-dictionary-by-values/
内容来源于网络,如有侵权,请联系作者删除!