对Map或Dictionary进行排序

x33g5p2x  于2022-10-05 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(474)

这个例子将展示如何在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
}

Map反向排序

@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
}

相关文章