Appendix A: Java/Groovy 1

Feature

Java

Groovy

Public class

public class

class

Loops

for(Type it : c){...}

c.each {...}

Lists

List list = asList(1,2,3);

def list = [1,2,3]

Maps

Map m = ...; m.put(x,y);

def m = [x: y]

Function definition

void method(Type t) {}

def method(t) {}

Mutable value

Type t

def t

Immutable value

final Type t

final t

Null safety

(x == null ? null : x.y)

x?.y

Null replacement

(x == null ? "y" : x)

x ?: "y"

Sort

Collections.sort(list)

list.sort()

Wildcard import

import java.util.*;

import java.util.*

Var-args

(String... args)

(String... args)

Type parameters

Class<T>

Class<T>

Concurrency

Fork/Join

GPars

No Java Analogue

Feature

Groovy

Default closure arg

it

Default value

def method(t = "yes")

Add method to object

Get Learning Groovy now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.