Library contents

Groovy String.compareTo

Check the ordering of two ASCII shelf labels before inserting one into a sorted display.

A simple example

String.compareTo

  1. Start with "a" and "b"
  2. Do this Compare their order
  3. Result a comes first
The first characters already differ. The code for a is smaller than the code for b.

Syntax

Groovy syntax
value.compareTo(other) < 0
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

Order two shelf areas

A directory orders shelf or room labels as text. Compare their spelling under the chosen ordering rule and check what happens when a label contains digits that look like a number.

From the programString value = "A-10"
Resultyes
Lesson.groovy
String value = "A-10"
String other = "B-10"
println((value.compareTo(other) < 0) ? "yes" : "no")
Output
yes

The first different letter places A before B.

Advertisements

Recognize tied course codes

A directory orders short labels entered using different capitalization. Decide when two entries should compare as a tie and when the comparison should place one label first.

From the programString value = "BIO"
Resultno
Lesson.groovy
String value = "BIO"
String other = "BIO"
println((value.compareTo(other) < 0) ? "yes" : "no")
Output
no

Equal codes do not precede each other.

Sort art studio lockers

A school uses two-letter locker prefixes. The catalog compares the two ASCII codes in text order. Which code sorts first?

Given'AR' · 'AT'
Worked resultAR

What to watch for

These examples assume ASCII shelf labels. Human names may require locale-aware collation.

Documentation for String.compareTo