用比较器语法进行常规排序

编程入门 行业动态 更新时间:2024-10-27 06:27:53
本文介绍了用比较器语法进行常规排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在用gremlin弄湿我的脚。我知道gremlin是基于groovy的。我发现这里的文档 ,但我仍然不确定语法是什么意思。

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

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

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

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

例如,如果您有列表 [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; } }

更多推荐

用比较器语法进行常规排序

本文发布于:2023-11-30 10:04:18,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法   常规

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!