最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

SEO心得admin130浏览0评论
本文介绍了用比较器语法进行常规排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在用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; } }

发布评论

评论列表(0)

  1. 暂无评论