RingJavafor Ring

Queries

jQuery filters, sorts, groups and totals a list with one chain of calls.

What you will learn#

The program#

samples/UsingJava/tutorials/ch22_queries.ring
# Tutorial 22: queries - filter, sort, group and total a list with jQuery
load "java.ring"

using {
	"java.util"
}

# 1. a list of rows: [name, city, age]
aPeople = [
	["Ali","Cairo",31],
	["Sara","Dubai",27],
	["Omar","Cairo",45],
	["Lina","Riyadh",38],
	["Zaid","Dubai",19]
]

# 2. filter and sort: the code of an operator is Ring text, x is the item
aOlder = jQuery(aPeople).filter("x[3] > 25").sortByDesc("x[3]").toList()
for aPerson in aOlder
	? aPerson[1] + " " + aPerson[3]
next

# 3. map, join and the values of a list
? jQuery(aPeople).sortBy("x[1]").map("x[1]").join(", ")
? "average age " + jQuery(aPeople).average("x[3]")
? "oldest " + jQuery(aPeople).sortByDesc("x[3]").first()[1]
? "anyone under 20? " + jQuery(aPeople).anyMatch("x[3] < 20")

# 4. group by a key: a list of [key, items]
for aGroup in jQuery(aPeople).sortBy("x[2]").groupBy("x[2]").toList()
	? aGroup[1] + ": " + jQuery(aGroup[2]).map("x[1]").join(", ")
next

# 5. sorting by two keys; the sort is stable
? jQuery(aPeople).sortBy("x[2]").thenByDesc("x[3]").map("x[1]").join(" ")

# 6. a function can be the operator: its name is given as text
? jQuery(jRange(1,10)).filter("isEven").map("x * x").join(" ")

# 7. a Java collection is a source too
oWords = new ArrayList
oWords.add("pear")
oWords.add("fig")
oWords.add("apple")
? jQuery(oWords).sortBy("len(x)").join(" < ")

# 8. reduce: x is the result so far and y the next item
? jQuery(jRange(1,5)).reduce(1,"x * y")

func isEven x
	return x % 2 = 0
Output
Omar 45
Lina 38
Ali 31
Sara 27
Ali, Lina, Omar, Sara, Zaid
average age 32
oldest Omar
anyone under 20? 1
Cairo: Ali, Omar
Dubai: Sara, Zaid
Riyadh: Lina
Omar Ali Sara Zaid Lina
4 16 36 64 100
fig < pear < apple
120

How it works#

Each operator gives a new query and leaves the list as it was, so a chain reads from left to right. The code of an operator is compiled once from its text; x is the item (and y the next item in reduce). A Java collection is copied to a Ring list at the start of the chain, one call into Java, and the rest runs in Ring. The sorts are stable, so sortBy("x[2]").thenByDesc("x[3]") and a sort by two keys give the same rows. See Queries for every operator.

Exercises#

  1. List the cities with the number of people in each.
  2. Print the three youngest names, oldest first.
  3. Make a query on the lines of a text file that Java reads for you.

Next#

Window builders

RingJava - use Java classes and methods from Ring programs.