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)
Java Groovy
1
Print a literal string on standard output
System.out.println("Hello World");
Alternative implementation:
out.print("Hello, World!");
println 'Hello World'
2
Loop to execute some code a constant number of times
for(int i=0;i<10;i++)
  System.out.println("Hello");
Alternative implementation:
System.out.print("Hello\n".repeat(10));
Alternative implementation:
int i = 0;
while (i++ < 10) out.println("Hello");
Alternative implementation:
for (int i = 0; i++ < 10; out.println("Hello"));
Alternative implementation:
int i = 0;
do out.println("Hello");
while (i++ < 10);
Alternative implementation:
range(0, 10).forEach(x -> out.println("Hello"));
Alternative implementation:
generate(() -> "Hello%n")
    .limit(10)
    .forEach(out::printf);
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){
  System.out.println("My job here is done. Goodbye " + name);
}
Alternative implementation:
private void methodName() {
	System.out.println("Hello, World!");
}
Alternative implementation:
void f() { out.println("abc"); }
Alternative implementation:
interface F { void set(); }
F f = () -> out.println("abc");
f.set();
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;
}
Alternative implementation:
Function<Integer,Integer> squareFunction = x -> x * x;
Alternative implementation:
int square(int a) { return a * a; }
Alternative implementation:
int square(int a) { return (int) pow(a, 2); }
Alternative implementation:
interface F { int get(int a); }
F square = x -> x * x;
Alternative implementation:
BigInteger square(BigInteger a) {
    return a.multiply(a);
}
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;
}
Alternative implementation:
class Point { double x, y; }
Alternative implementation:
public record Point(double x, double y) { }
Alternative implementation:
record Point<T extends Number>(T x, T y) {}
class Point{
  double x
  double y
}
6
Do something with each item x of the list (or array) items, regardless indexes.
for (Item x: items) {
    doSomething(x);
}
Alternative implementation:
for(int i=0;i<items.length;i++){
	doSomething( items[i] );
}
Alternative implementation:
items.stream().forEach(item -> doSomething(item));
Alternative implementation:
for (T x : items) {}
Alternative implementation:
T t;
Iterator<T> i = items.iterator();
while (i.hasNext()) {
    t = i.next();
}
Alternative implementation:
T t;
Iterator<T> i = items.listIterator();
while (i.hasNext()) {
    t = i.next();
}
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
int i, n;
for (i = 0, n = items.length; i < n; ++i)
    out.println(i + " = " + items[i]);
Alternative implementation:
int i, n;
for (i = 0, n = items.size(); i < n; ++i)
    out.println(i + " = " + items.get(i));
Alternative implementation:
int i = 0;
for (T t : items)
    out.println(i++ + " = " + t);
Alternative implementation:
range(0, items.length)
    .forEach(i -> {
        out.println(i + " = " + items[i]);
    });
items.eachWithIndex {
  x, i -> println "Item $i = $x"
}
8
Create a new map object x, and provide some (key, value) pairs as initial content.
Map<String,Integer> x = new HashMap<>();
x.put("one", 1);
x.put("two", 2);
Alternative implementation:
final Map<String, Integer> x = new HashMap<String, Integer>() {{
    put("one", 1);
    put("two", 2);
    put("three", 3);
}};
Alternative implementation:
Map<String, Integer> x = of("x", 1, "y", 2);
Alternative implementation:
Entry<String, Integer> a = entry("x", 1),
                       b = entry("y", 2);
Map<String, Integer> x = ofEntries(a, b);
Alternative implementation:
Map<String, Integer> x = new HashMap<>(of("x", 1, "y", 2));
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;
}
Alternative implementation:
interface Tree<T>{
    boolean search(T x);
}
class Nil<T extends Comparable<? super T>> implements Tree<T>{
    public boolean search(T x) { return false; }
}
class Node<T extends Comparable<? super T>> implements Tree<T> {
 T item;  Tree<T> left; Tree<T> right;
 public Node(T i, Tree<T> l, Tree<T> r) {
     item=i;  left=l;  right=r; }
 public boolean search(T x) {
     int cmp = x.compareTo(item);
     return cmp==0 || (cmp<0 && left.search(x)) || (cmp>0 && right.search(x));
 }
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
Collections.shuffle(x);
Alternative implementation:
shuffle(asList(x));
x.shuffle()
11
The list x must be non-empty.
x.get((int)(Math.random()*x.size()))
Alternative implementation:
x.get(ThreadLocalRandom.current().nextInt(0, x.size()))
Alternative implementation:
if (!x.isEmpty()) {
    Random r = new Random();
    T t = x.get(r.nextInt(x.size()));
}
x.shuffled().first()
12
Check if the list contains the value x.
list is an iterable finite container.
boolean contains(int[] list, int x){
  for(int y:list)
    if( y==x )
      return true;
  return false;
}
Alternative implementation:
boolean <T> contains(T[] list, T x){
  if( x==null){
    for(T y:list)
      if( y==null )
        return true;
  }else{
    for(T y:list)
      if( x.equals(y) )
        return true;
  }
  return false;
}
Alternative implementation:
list.contains(x)
Alternative implementation:
asList(list).contains(x);
list.contains(x)
13
Access each key k with its value x from an associative array mymap, and print them.
for (Map.Entry<Object, Object> entry : mymap.entrySet()) {
    Object k = entry.getKey();
    Object x = entry.getValue();
    System.out.println("Key=" + k + ", Value=" + x);
}
Alternative implementation:
mymap.forEach((k,x) -> System.out.println("Key=" + k + ", Value=" + x));
Alternative implementation:
K k;
X x;
for (Entry<K, X> e : mymap.entrySet()) {
    k = e.getKey();
    x = e.getValue();
    out.println(e);
}
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
void dfs(BinTree bt) {
	if (bt.left != null) {
		dfs(bt.left);
        }
	f(bt);
	if (bt.right != null) {
		dfs(bt.right);
        }
}
Alternative implementation:
class BinTree {
	// ...

	void dfs() {
		if( left != null )
			left.dfs();
		f(this);
		if( right != null )
			right.dfs();
	}
}
Alternative implementation:
class BinTree<T> {
	// ...

	void dfs(Consumer<BinTree<T>> f) {
		if( left != null )
			left.dfs(f);
		f.accept(this);
		if( right != null )
			right.dfs(f);
	}
}
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.
static <T> void reverse(List<T> x){
	int n = x.size();
	for(int i=0;i<n/2;i++){
		T tmp = x.get(i);
		x.set(i, x.get(n-i-1));
		x.set(n-i-1, tmp);
	}
}
Alternative implementation:
Collections.reverse(x);
Alternative implementation:
Collections.reverse(x);
Alternative implementation:
int i, m = x.size(), n = m-- / 2;
for (i = 0; i < n; ++i) swap(x, i, m - i);
Alternative implementation:
reverse(x);
x = x.reverse()
21
Swap the values of the variables a and b
T tmp = a;
a = b;
b = tmp;
(a, b) = [b, a]
22
Extract the integer value i from its string representation s (in radix 10)
int i = Integer.parseInt(s);
Alternative implementation:
int i = new Integer(s).intValue();
Alternative implementation:
Integer i = Integer.valueOf(s, 10);
Alternative implementation:
int i = s.chars()
     .map(x -> x - '0')
     .reduce((a, b) -> (a * 10) + b)
     .getAsInt();
Integer i = s.toInteger()
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.
Arrays.sort(items, new Comparator<Item>(){
	public int compare(Item a, Item b){
		return a.p - b.p;
	}
});
Alternative implementation:
Collections.sort(items, new Comparator<Item>(){
	@Override
	public int compare(Item a, Item b){
		return a.p - b.p;
	}
});
Alternative implementation:
items.stream().sorted(Comparator.comparing(x -> x.p))
Alternative implementation:
sort(items, comparing(x -> x.p));
Alternative implementation:
items.sort(comparing(a -> a.p));
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)
int f(int i) {
    if (i == 0)
        return 1;
    else
        return i * 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.
String t = s.substring(i,j);
def t = s[i..<j]
46
Create the string t consisting of the 5 first characters of the string s.
Make sure that multibyte characters are properly handled.
String t = s.substring(0,5);
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.
String t = s;
if (s.length()>= 5)
	t = s.substring(s.length()-5);
Alternative implementation:
int i = s.length() - 5;
if (isSurrogate(s.charAt(i))) --i;
String t = s.substring(i);
final t = s[-5..-1]
48
Assign to variable s a string literal consisting in several lines of text, including newlines.
String s = "This is a very long string which needs \n" +
           "to wrap across multiple lines because \n" +
           "otherwise my code is unreadable.";
Alternative implementation:
String s = """
This is a very long string which needs
to wrap across multiple lines because
otherwise my code is unreadable.
""";
Alternative implementation:
String s, n = lineSeparator();
s = "line 1" + n;
s = s + "line 2" + n;
s = s + "line 3" + n;
s = s + "line 4";
Alternative implementation:
String s;
StringBuilder b = new StringBuilder();
Formatter f = new Formatter(b);
f.format("line 1%n");
f.format("line 2%n");
f.format("line 3%n");
f.format("line 4");
f.flush();
s = b.toString();
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 the string s, separated by one or more space characters.
String chunks[] = s.split(" +");
Alternative implementation:
List<String> chunks = of(s.split(" +"));
Alternative implementation:
List<String> chunks = asList(s.split(" +"));
Alternative implementation:
Scanner t = new Scanner(s);
t.useDelimiter(compile(" +"));
List<String> chunks = t.tokens().toList();
t.close();
Alternative implementation:
Scanner t = new Scanner(s);
t.useDelimiter(compile(" +"));
String chunks[] = t.tokens()
    .toArray(String[]::new);
t.close();
Alternative implementation:
List<String> chunks
    = new ArrayList<>(of(s.split(" +")));
def chunks = s.split(/\s+/)
50
Write a loop that has no end clause.
for(;;){
	// Do something
}
Alternative implementation:
while(true) {
	// Do something	
}
Alternative implementation:
do {} while (true);
Alternative implementation:
while (true);
Alternative implementation:
for (;;);
while (true) { }
53
Concatenate elements of string list x joined by the separator ", " to create a single string y.
String y = String.join(", ", x);
Alternative implementation:
String y = x.get(0);
int i = 1, n = x.size();
while (i < n)
    y = y + ", " + x.get(i++);
Alternative implementation:
String y = x.stream()
    .reduce((a, b) -> a + ", " + b)
    .get();
String y = x.join(', ')
55
Create the string representation s (in radix 10) of the integer value i.
String s=((Integer)i).toString();
Alternative implementation:
String s = Integer.toString(i);
Alternative implementation:
String s = String.valueOf(i);
Alternative implementation:
String s = "" + i;
Alternative implementation:
String s = "%d".formatted(i);
Alternative implementation:
String s = "";
while (i != 0) {
    s = i % 10 + s;
    i = i / 10;
}
def s = "$i".toString()
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.
List<T> y = x.stream().filter(p).toList();
Alternative implementation:
List<T> y = new ArrayList<>();
for (T t : x) if (p.test(t)) y.add(t);
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).
int y = (int)x;
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);
Alternative implementation:
<T> void f(T x) {
    Objects.requireNonNull(x);
}
Alternative implementation:
<T> void f(T x) throws Exception {
    if (x != value) throw new Exception();
}
Alternative implementation:
void f(int x) {
    Objects.checkIndex(x, 123);
}
throw new IllegalArgumentException("Invalid value for x: $x")
93
Implement the procedure control which receives one parameter f, and runs f.
static void control(Runnable f) {
    f.run();
}
Alternative implementation:
control: Callable = lambda f: f()
void control(Closure f) {
    f()
}
97
Set boolean b to true if string s ends with string suffix, false otherwise.
boolean b = s.endsWith(suffix);
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 = HttpClient.newHttpClient().send(HttpRequest.newBuilder()
                .uri(URI.create(u))
                .GET()
                .build(), HttpResponse.BodyHandlers.ofString())
                .body();
Alternative implementation:
HttpsURLConnection h = null;
try {
    h = (HttpsURLConnection) u.openConnection();
    h.setRequestMethod("GET");
    byte a[] = h.getInputStream().readAllBytes();
    String s = new String(a);
} catch (IOException e) {
    throw new RuntimeException(e);
} finally {
    if (h != null) h.disconnect();
}
String s = u.text
106
Assign to string dir the path of the working directory.
(This is not necessarily the folder containing the executable itself)
String path = this.getClass().getClassLoader().getResource("").getPath();
Alternative implementation:
String dir = new File("").getAbsolutePath();
Alternative implementation:
String dir = System.getProperty("user.dir");
def dir = new File('.').absolutePath
112
Print each key k with its value x from an associative array mymap, in ascending order of k.
SortedMap<K, V> mymap = new TreeMap<>();
...
for(Map.Entry<K, V> e: mymap.entrySet())
	System.out.println("Key=" + e.getKey() + ", Value=" + e.getValue());
Alternative implementation:
List<K> keys = new ArrayList<>(mymap.keySet());
Collections.sort(keys);
for(K k: keys)
	System.out.println("Key=" + k + ", Value=" + mymap.get(k));
Alternative implementation:
var map = Map.of("a", 1, "d", 4, "c", 3, "b", 2);
new TreeMap<>(map).entrySet().forEach(System.out::println);
Alternative implementation:
mymap.entrySet().stream().sorted(Entry.comparingByKey()).forEach(System.out::println);
Alternative implementation:
for (Entry<K, V> e : new TreeMap<>(m).entrySet())
    out.println(e);
Alternative implementation:
mymap.entrySet()
    .stream()
    .sorted(comparingByKey())
    .forEach(e -> {
        K k = e.getKey();
        X x = e.getValue();
        out.println(e);
    });
mymap.sort { it.key }.each { println it}
115
Set boolean b to true if date d1 is strictly before date d2 ; false otherwise.
boolean before = (d1.compareTo(d2) == -1);
boolean b = d1.before(d2)
117
Set n to the number of elements of the list x.
int n = x.size();
Alternative implementation:
int n = x.length;
def n = x.size()
119
Remove duplicates from the list x.
Explain if the original order is preserved.
Set<T> uniques = new HashSet<>(x);
x.clear();
x.addAll(uniques);
Alternative implementation:
x = new ArrayList<T>(new HashSet<T>(x));
Alternative implementation:
final HashSet<T> seen = new HashSet<T>();
final Iterator<T> listIt = x.iterator();
while (listIt.hasNext()) {
  final T curr = listIt.next();
  if (seen.contains(curr)) {
    listIt.remove();
  } else {
    seen.add(curr);
  }
}
Alternative implementation:
x = new ArrayList<>(new LinkedHashSet<>(x));
Alternative implementation:
Iterator<T> g;
T t;
int i, n;
for (i = 0, n = x.size(); i < n; ++i) {
    t = x.get(i);
    g = x.listIterator(i + 1);
    while (g.hasNext())
        if (g.next().equals(t)) {
            g.remove();
            --n;
        }
}
x.unique()
122
Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS.
enum Suit{
  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() : "State consistency violated";
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();
}
Alternative implementation:
if (c1) f1();
else if (c2) f2();
else if (c3) f3();
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.
List<T> items = new ArrayList<>();
items.add(a);
items.add(b);
items.add(c);
Alternative implementation:
List<T> items = Arrays.asList(a, b, c);
Alternative implementation:
var items = List.of(a, b, c);
Alternative implementation:
List<T> items = new ArrayList<>(of(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.
Logger LOGGER = Logger.getLogger(MyClass.class.getName());

LOGGER.info(msg);
Alternative implementation:
out.printf("%tc:  `%s`%n", currentTimeMillis(), msg);
@Slf4j
class X {
    def m(String message) {
        log.debug(message)
    }
}
157
Initialize a constant planet with string value "Earth".
static final String planet = "Earth";
Alternative implementation:
final String planet = "Earth";
Alternative implementation:
final String planet = "Earth";
static final planet = "Earth"
static final planet = 'Earth'
static final planet = /Earth/
static final planet = '''Earth'''
static final planet = """Earth"""
165
Assign to the variable x the last element of the list items.
int x = items[items.length - 1];
Alternative implementation:
T x = items.getLast();
def x = items.last()
170
Set n to the number of elements stored in mymap.

This is not always equal to the map capacity.
int n = mymap.size();
def n = mymap.size()
172
Insert value v for key k in map m.
m.put(k, v);
m.k = v
Alternative implementation:
m[k] = v
175
From the 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).
String s = "";
for (byte b : a)
    s = s + "%02x".formatted(b);
Alternative implementation:
var s = HexFormat.of().formatHex(a);
Alternative implementation:
String s = range(0, n)
    .mapToObj(x -> a[x])
    .map("%02x"::formatted)
    .reduce(String::concat)
    .get();
def s = a.encodeHex().toString()
184
Assign to t a string representing the day, month and year of the day after the current date.
String t = LocalDate.now().plusDays(1).toString();
LocalDate t = LocalDate.now() + 1
185
Schedule the execution of f(42) in 30 seconds.
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule(() -> _f(42), delayInSeconds, TimeUnit.SECONDS);
Alternative implementation:
Thread t = new Thread(() -> {
    try {
        sleep(30_000);
        f(42);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
});
t.start();
sleep(30*1000)
f(42)
189
Produce a new list y containing the result of the function T applied to all elements e of the list x that match the predicate P.
x.stream().filter(P).map(T).collect(Collectors.toList());
Alternative implementation:
List<T> y = x.stream()
             .filter(P)
             .map(T)
             .toList();
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
for(int i = 0; i<a.length;i++) {
	if(a[i]>x) {
		f();
		break;
	}
}
Alternative implementation:
for (int i : a)
    if (i > x) {
        f();
        break;
    }
Alternative implementation:
if (of(a).anyMatch(i -> i > x)) f();
if (a.any { it > x })
    f()
202
Calculate the sum of squares s of data, an array of floating point values.
double s = Arrays.stream(data).map(i -> i * i).sum();
Alternative implementation:
double s = of(data).map(x -> x * x).sum();
Alternative implementation:
BigDecimal s = of(data)
    .mapToObj(String::valueOf)
    .map(BigDecimal::new)
    .map(x -> x.multiply(x))
    .reduce(BigDecimal::add)
    .get();
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".
String foo = System.getenv("foo");
if (foo == null) {
	foo = "none";
}
Alternative implementation:
String foo;
try {
    foo = getenv("FOO");
    if (foo == null) throw new Exception();
} catch (Exception e) {
    foo = "none";
}
def foo = System.getenv('FOO') ?: 'none'
210
Assign, at runtime, the compiler version and the options the program was compiled 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
public static void main(String[] args) {
    String version = getProperty("java.vm.version"),
           options = join(" ", args);
}
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.
String t = s.replaceAll(" +", " ");
Alternative implementation:
String t = s.replaceAll("\\s+", " ");
Alternative implementation:
String t = s.replaceAll(" {2,}", " ");
Alternative implementation:
String t = join(" ", s.split(" +", -1));
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.
boolean b = false;
for (int i = 0; i<items.length; i++) {
	if (items[i] == something) {
		doSomething();
		b = true;
	}
}
if (!b)
	doSomethingElse();
Alternative implementation:
Predicate<Item> condition;
items.stream()
	.filter(condition)
	.findFirst()
	.ifPresentOrElse(
		item -> doSomething(i),
		() -> doSomethingElse());
Alternative implementation:
 a: {
     b: {
            int i, n = items.size();
            for (i = 0; i < n; ++i)
                if (f(items.get(i)))
                    break b;
            out.println("not found");
            break a;
        }
        out.println("found");
    }
println(items.any { it == "baz" } ? 'found' : 'not found')
228
Copy the file at path src to dst.
Files.copy(Path.of(src), Path.of(dst));
new File(dst).bytes = new File(src).bytes
Alternative implementation:
new File(src).withInputStream { input ->
    new File(dst).withOutputStream {output ->
        output << input
    }
}

234
Assign to the string s the standard base64 encoding of the byte array data, as specified by RFC 4648.
byte data[] = s.getBytes();
String s = getEncoder().encodeToString(data);
final s = data.encodeBase64().toString()
235
Assign to byte array data the bytes represented by the base64 string s, as specified by RFC 4648.
byte[] data = Base64.getDecoder().decode(s);
final data = s.decodeBase64()
357
Swap the elements at indices i, j in the list items
swap(items, i, j);
items.swap(i, j)