用比较器语法进行常规排序 [英] groovy sort with comparator syntax

查看:84
本文介绍了用比较器语法进行常规排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用gremlin弄湿我的脚。我知道gremlin是基于groovy的。我发现这里的文档 < a>,但我仍然不确定语法是什么意思。



对于比较器的排序语法如何工作,我有点困惑:

  m.sort {a,b  - > a.value => b.value} 

有人可以解释 { } 是什么意思? > Closure 被使用时排序 有两个参数,它像一个传统的 比较 。也就是说,对于在排序过程中进行的每个比较,在两个元素 a b 之间进行比较,返回一个负整数,零或一个正整数,因为第一个参数小于,等于或大于第二个。



在您的特定场景中,比较结果是使用太空船运营商 < = > 。换句话说,您正在按升序顺序排列元素。

例如,如果您有列表<$ c $> [3,2,1] ,使用该排序的结果 m.sort {a,b - > a.value => b.value} 大致等于使用下面的 compare 函数:

  int compare(a,b){
if(a< b){
return -1;
} else else if(a> b){
return 1;
} else {
return 0;
}
}


I am just getting my feet wet with gremlin. I understand that gremlin is based on groovy. I found the documentation here, but I am still not sure what the syntax means.

I am a bit confused as to how the syntax of sort with a comparator works:

m.sort{a,b -> a.value <=> b.value}

Could someone explain what all the different bits between the { and } mean?

解决方案

When the Closure used by sort has two parameters, it acts like a traditional Comparator. That is, for each comparison that is done during the sort, between two elements a and b, it returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

In your particular scenario, the comparison is the result of using the spaceship operator <=>. In other words, you are effectively sorting your elements in ascending order.

For example, if you had the list [ 3, 2, 1 ], the result of using that sort would be [ 1, 2, 3 ].

Thus, m.sort{a,b -> a.value <=> b.value} is roughly the equivalent of using the following compare function:

int compare(a, b) {
  if (a < b) {
    return -1;
  } else if (a > b) {
    return 1;
  } else {
    return 0;
  }
}

这篇关于用比较器语法进行常规排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆