Accueil / Java Techs / Groovy / L’opérateur de spaceship Groovy a expliqué

L’opérateur de spaceship Groovy a expliqué

Print Friendly, PDF & Email

Have you ever heard of the spaceship operator? If it is the case, how does it look like? To be honest, I have known it recently when I used this comparison operator to sort an array list of objects. In this post, I will show you what the operator does and how could we apply it into realistic situations.

What is it?

Spaceship operator, originally called three-way comparison and spelt <=>, is used for comparing two objects A and B. This operator returns the values −1, 0, or 1 depending on whether A < B, A = B, or A > B, respectively. There have been a few reasons why it was historically named “spaceship operator” [1]. In my honest opinion, the two symbols < and > look the heads of a spaceship while the symbol = seems to be the body of the spaceship.

PHP 7 introduced the spaceship operator as a new feature [4, 5]. The upcoming C++ spaceship operator has been approved in the proposals for the next C++ standardisation [6, 7].

Spaceship operator In Groovy

Let’s give a piece of code listed below.

That piece of code aims to compare Date objects. Obviously, we can evaluate the output of the last three printlnstatement. They produce 0, 1, -1, respectively.

To illustrate what we have done in our work, I will present below how to sort entries of Model of The Month by the publication date. Let’s look at the following lines:

This results RSS feeds where all entries of Model of The Month were ordered descending by the publication date. See the screenshot below.

In practice, the spaceship operator is often used for sorting objects in arrays or lists. To write this article, I have read the section Spaceship Operator in Groovy’s documentation [2] and a glorious explanation [3].

References

[1] Three-way comparison

[2] Spaceship Operator

[3] The Groovy Spaceship Operator Explained

[4] New features in PHP7

[5] What does this symbol mean in PHP?

[6] Proposals to Fix the Spaceship Operator

[7] Mathematics behind Comparison #1: Equality and Equivalence Relations

comments

À propos Nguyen Vu Ngoc Tung

I love making new professional acquaintances. Don't hesitate to contact me via nguyenvungoctung@gmail.com if you want to talk about information technology, education, and research on complex networks analysis (i.e., metabolic networks analysis), data analysis, and applications of graph theory. Specialties: researching and proposing innovative business approaches to organizations, evaluating and consulting about usability engineering, training and employee development, web technologies, software architecture.