RingJavafor Ring

Collections and streams

Lists, maps and sets of Java, sorting with a Ring function, and streams that filter, map and collect.

What you will learn#

The program#

samples/UsingJava/tutorials/ch04_collections.ring
# Tutorial 4: collections - List, Map, Set, Collections and streams
load "java.ring"

using {
	"java.lang"
	"java.util"
	"java.util.stream"
}

Collections = new Collections
Collectors = new Collectors

# a list: a Ring list goes where Java wants a collection, toList() gives a Ring list back
oNames = new ArrayList(["pear","apple","fig","banana"])
Collections.sort(oNames)
? oNames.toString()
? oNames.@get(0) + " ... " + oNames.@get(oNames.size() - 1)
oNames.add([ :index = 0 , :element = "cherry" ])
? oNames.indexOf("fig")
? oNames.contains("apple")
aNames = oNames.toList()
for cName in aNames
	see cName + " "
next
? ""

# a map: put and get are words of Ring, so they are @put and @get
oAges = new LinkedHashMap
oAges.@put("Ann",31)
oAges.@put("Bob",27)
oAges.@put("Cy",45)
? oAges.@get("Bob")
? oAges.getOrDefault("Dee",0)
aPairs = oAges.toList()
for aPair in aPairs
	? aPair[1] + " is " + aPair[2]
next
? oAges.keySet().toString()

# a set: no duplicates
oSet = new TreeSet([5,1,3,1,5,3])
? oSet.toString()
? oSet.first()

# sorting with a Ring function that Java calls
oNames.sort("xJavaResult = len(aJavaArgs[1]) - len(aJavaArgs[2])")
? oNames.toString()

# streams: filter, map, collect
oNumbers = new ArrayList([1,2,3,4,5,6,7,8,9,10])
? oNumbers.stream().filter("xJavaResult = aJavaArgs[1] % 2 = 0").count()
oSquares = oNumbers.stream().map("xJavaResult = aJavaArgs[1] * aJavaArgs[1]").collect(Collectors.@toList())
? oSquares.toString()
? oNumbers.stream().mapToInt("xJavaResult = aJavaArgs[1]").sum()
Output
[apple, banana, fig, pear]
apple ... pear
3
1
cherry apple banana fig pear 
27
0
Ann is 31
Bob is 27
Cy is 45
[Ann, Bob, Cy]
[1, 3, 5]
1
[fig, pear, apple, cherry, banana]
5
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
55

How it works#

A Ring list goes where a Java Collection is expected, and toList() turns a Java collection into a Ring list. put and get are keywords of Ring, so the methods of a Java Map are written @put and @get; the same @ prefix is used for every Java name that is a word of Ring.

A text can be code: oNames.sort("xJavaResult = len(aJavaArgs[1]) - len(aJavaArgs[2])") runs that Ring code for each comparison (a text that is the name of a Ring function works too). A stream pipeline (filter, map, collect) takes Ring code or function names in the same way.

Exercises#

  1. Count how often each word occurs in a list, using a HashMap.
  2. Sort the words by their last letter.
  3. Keep only the numbers above 10 with a stream.

Next#

Dates and times

RingJava - use Java classes and methods from Ring programs.