对Map或Dictionary进行排序

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

这个例子将展示如何在groovy中按值对Map或Dictionary进行排序。如果你有一个域,一个键和值的表,你可能想用描述的顺序来显示一个下拉菜单。如果你不能通过数据库排序,一个直接的方法是按值对Map进行排序。我从gmail中提取了一些用于邮件操作的样本值。

我们将使用groovy spaceship operator。对于按值反向排序的map,我们只需切换我们要比较的内容。

按值排序

  1. @Test
  2. void sort_map_by_value() {
  3. def myMap = [1:"More", 2:"Mark as read", 3: "Mark as important", 4:"Add to tasks"]
  4. assert [
  5. "Add to tasks",
  6. "Mark as important",
  7. "Mark as read",
  8. "More"] == myMap.sort({a, b -> a.value <=> b.value})*.value
  9. }

Map反向排序

  1. @Test
  2. void sort_map_by_value_reverse() {
  3. def myMap = [1:"More", 2:"Mark as read", 3: "Mark as important", 4:"Add to tasks"]
  4. assert [
  5. "More",
  6. "Mark as read",
  7. "Mark as important",
  8. "Add to tasks"] == myMap.sort({a, b -> b.value <=> a.value})*.value
  9. }

按值排序,不区分大小写

  1. @Test
  2. void sort_map_by_value_case_insensitive() {
  3. def myMap = [1:"More", 2:"Mark as read", 3: "Mark as important", 4:"Add to tasks"]
  4. assert [
  5. "Add to tasks",
  6. "Mark as important",
  7. "Mark as read",
  8. "More"] == myMap.sort({a, b -> a.value.toLowerCase() <=> b.value.toLowerCase()})*.value
  9. }

相关文章