The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0

Logo

Programming-Idioms.org

  • The snippets are under the CC-BY-SA license.
  • Please consider keeping a bookmark
  • (instead of printing)
Groovy
1
Print a literal string on standard output
println 'Hello World'
2
Loop to execute some code a constant number of times
10.times {
    println 'Hello'
}‚Äč
3
Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
void finish(String name){
  println "My job here is done. Goodbye $name"
}
4
Create a function which returns the square of an integer
int square(int x){
  return x*x
}
5
Declare a container type for two floating-point numbers x and y
class Point{
  double x
  double y
}
6
Do something with each item x of an array-like collection items, regardless indexes.
items.each { x -> doSomething(x) }
Alternative implementation:
for(x in items) doSomething(x)
Alternative implementation:
items.each { doSomething(it) }
7
Print each index i with its value x from an array-like collection items
items.eachWithIndex {
  x, i -> println "Item $i = $x"
}
8
Create a new map object x, and provide some (key, value) pairs as initial content.
def x = ['un':1, 'dos':2, 'tres':3]
Alternative implementation:
def x = [un:1, dos:2, tres:3]
9
The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.
class BinTree<T extends Comparable<T>>{
   T value
   BinTree<T> left
   BinTree<T> right
}
10
Generate a random permutation of the elements of list x
x.shuffle()
12
Check if the list contains the value x.
list is an iterable finite container.
list.contains(x)
13
Access each key k with its value x from an associative array mymap, and print them.
mymap.each { k, x ->
	println "Key $k - Value $x"
}
16
Call a function f on every node of binary tree bt, in depth-first infix order
class BinTree {
    BinTree left
    BinTree right

    void dfs(Closure f) {
        left?.dfs(f)
        f.call(this)
        right?.dfs(f)
    }
}
19
Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.
x = x.reverse()
28
Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.
items.sort { x -> x.p }
Alternative implementation:
items.sort { x, y -> x.p <=> y.p }
31
Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)
def f(i) { i == 0 ? 1 : i * f(i - 1) }
38
Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.
def t = s[i..<j]
46
Create string t consisting of the 5 first characters of string s.
Make sure that multibyte characters are properly handled.
def t = s.take(5)
Alternative implementation:
def t = s[0..<5]
47
Create string t consisting in the 5 last characters of string s.
Make sure that multibyte characters are properly handled.
final t = s[-5..-1]
48
Assign to variable s a string literal consisting in several lines of text, including newlines.
def s = """line 1
line 2
line 3"""
Alternative implementation:
def s = """\
	line 1
	line 2
	line 3""".stripIndent()
49
Build list chunks consisting in substrings of input string s, separated by one or more space characters.
def chunks = s.split(/\s+/)
53
Concatenate elements of string list x joined by the separator ", " to create a single string y.
String y = x.join(', ')
57
Create the list y containing the items from the list x that satisfy the predicate p. Respect the original ordering. Don't modify x in-place.
def y = x.findAll(p)
80
Declare integer y and initialize it with the value of floating point number x . Ignore non-integer digits of x .
Make sure to truncate towards zero: a negative x must yield the closest greater integer (not lesser).
def y = x as int
89
You've detected that the integer value of argument x passed to the current function is invalid. Write the idiomatic way to abort the function execution and signal the problem.
throw new IllegalArgumentException("Invalid value for x: $x")
92
Write the contents of the object x into the file data.json.
new File("data.json").text = new JsonBuilder(x).toPrettyString()
93
Implement procedure control which receives one parameter f, and runs f.
void control(Closure f) {
    f()
}
97
Set boolean b to true if string s ends with string suffix, false otherwise.
final b = s.endsWith(suffix)
101
Make an HTTP request with method GET to the URL u, then store the body of the response in the string s.
String s = u.text
103
Read from the file data.xml and write its contents into the object x.
Assume the XML data is suitable for the type of x.
def x = new XmlSlurper().parse(new File('data.xml'))
106
Assign to string dir the path of the working directory.
(This is not necessarily the folder containing the executable itself)
def dir = new File('.').absolutePath
112
Print each key k with its value x from an associative array mymap, in ascending order of k.
mymap.sort { it.key }.each { println it}
115
Set boolean b to true if date d1 is strictly before date d2 ; false otherwise.
boolean b = d1.before(d2)
117
Set n to the number of elements of the list x.
def n = x.size()
119
Remove duplicates from the list x.
Explain if the original order is preserved.
x.unique()
122
Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS.
enum Suit{
  SPADES,
  HEARTS,
  DIAMONDS,
  CLUBS
}
123
Verify that predicate isConsistent returns true, otherwise report assertion violation.
Explain if the assertion is executed even in production environment or not.
assert isConsistent()
131
Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.
Don't evaluate a condition when a previous condition was true.
if (c1) {
   f1()
} else if (c2) {
   f2()
} else if (c3) { 
   f3()
}
134
Declare and initialize a new list items, containing 3 elements a, b, c.
def items = [a, b, c]
145
Print message msg, prepended by current date and time.

Explain what behavior is idiomatic: to stdout or stderr, and what the date format is.
@Slf4j
class X {
    def m(String message) {
        log.debug(message)
    }
}
157
Initialize a constant planet with string value "Earth".
static final planet = "Earth"
static final planet = 'Earth'
static final planet = /Earth/
static final planet = '''Earth'''
static final planet = """Earth"""
170
Set n to the number of elements stored in mymap.

This is not always equal to the map capacity.
def n = mymap.size()
172
Insert value v for key k in map m.
m.k = v
Alternative implementation:
m[k] = v
175
From array a of n bytes, build the equivalent hex string s of 2n digits.
Each byte (256 possible values) is encoded as two hexadecimal characters (16 possible values per digit).
def s = a.encodeHex().toString()
184
Assign to variable t a string representing the day, month and year of the day after the current date.
LocalDate t = LocalDate.now() + 1
185
Schedule the execution of f(42) in 30 seconds.
sleep(30*1000)
f(42)
189
Produce a new list y containing the result of function T applied to all elements e of list x that match the predicate P.
def y = x.findAll(p).collect(t)
191
Given a one-dimensional array a, check if any value is larger than x, and execute the procedure f if that is the case
if (a.any { it > x })
    f()
202
Calculate the sum of squares s of data, an array of floating point values.
def s = data.sum { it ** 2 }
205
Read an environment variable with the name "FOO" and assign it to the string variable foo. If it does not exist or if the system does not support environment variables, assign a value of "none".
def foo = System.getenv('FOO') ?: 'none'
210
Assign, at runtime, the compiler version and the options the program was compilerd with to variables version and options, respectively, and print them. For interpreted languages, substitute the version of the interpreter.

Example output:

GCC version 10.0.0 20190914 (experimental)
-mtune=generic -march=x86-64
version = GroovySystem.version
219
Create the string t from the value of string s with each sequence of spaces replaced by a single space.

Explain if only the space characters will be replaced, or the other whitespaces as well: tabs, newlines.
def t = s.replaceAll(/\s+/, ' ')
223
Loop through list items checking a condition. Do something else if no matches are found.

A typical use case is looping through a series of containers looking for one that matches a condition. If found, an item is inserted; otherwise, a new container is created.

These are mostly used as an inner nested loop, and in a location where refactoring inner logic into a separate function reduces clarity.
println(items.any { it == "baz" } ? 'found' : 'not found')
228
Copy the file at path src to dst.
new File(dst).bytes = new File(src).bytes
Alternative implementation:
new File(src).withInputStream { input ->
    new File(dst).withOutputStream {output ->
        output << input
    }
}

231
Set b to true if the byte sequence s consists entirely of valid UTF-8 character code points, false otherwise.
final decoder = UTF_8.newDecoder()
final buffer = ByteBuffer.wrap(s)
try {
    decoder.decode(buffer)
    b = true
} catch (CharacterCodingException e) {
    b = false
}
234
Assign to string s the standard base64 encoding of the byte array data, as specified by RFC 4648.
final s = data.encodeBase64().toString()
235
Assign to byte array data the bytes represented by the base64 string s, as specified by RFC 4648.
final data = s.decodeBase64()