Summary of mutual conversion between Groovy's Default Groovy Methods and Java's Stream API

At work, I rewrote Groovy's Default Groovy Methods into a form using Java's Stream API, so I will summarize it as a memorandum.

The operation of the sample code has been confirmed in the following versions. Java: 11 Groovy: 2.5.8

DefaultGroovyMethod ⇔ Stream API each ⇔ forEach

Groovy


def list = ["Java", "Groovy", "Scala"]
list.each { println it }

---result---
Java
Groovy
Scala

Java


List<String> list = List.of("Java", "Groovy", "Scala");
list.forEach(System.out::println);

---result---
Java
Groovy
Scala

collect ⇔ map + collect

Groovy


def lowerCases = ["java", "groovy", "scala"]
def upperCases = lowerCases.collect { it.toUpperCase() } 
println upperCases

---result---
[JAVA, GROOVY, SCALA]

Java


List<String> lowerCases = List.of("java", "groovy", "scala");
List<String> upperCases = lowerCases.stream().map(language -> language.toUpperCase()).collect(Collectors.toList());
System.out.println(upperCases);

---result---
[JAVA, GROOVY, SCALA]

findAll ⇔ filter + collect

Groovy


def numbers = [1, 2, 3, 4, 5] 
def odds = numbers.findAll { it % 2 != 0 } 
println odds

---result---
[1, 3, 5]

Java


List<Integer> numbers = List.of(1, 2, 3, 4, 5);
List<Integer> odds = numbers.stream().filter(number -> number % 2 != 0).collect(Collectors.toList());
System.out.println(odds);

---result---
[1, 3, 5]

Reference material

Official reference

List https://docs.oracle.com/javase/jp/8/docs/api/java/util/List.html Stream https://docs.oracle.com/javase/jp/8/docs/api/java/util/stream/Stream.html Collectors https://docs.oracle.com/javase/jp/8/docs/api/java/util/stream/Collectors.html

DefaultGroovyMethods http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html

Qiita article

Groovy methods that are likely to be used (List) https://qiita.com/kimromi/items/e326bf9c24220df97ecf

Recommended Posts

Summary of mutual conversion between Groovy's Default Groovy Methods and Java's Stream API
Let's consider the meaning of "stream" and "collect" in Java's Stream API.
[Swift] Mutual conversion between Int and Data
Notes on Java's Stream API and SQL
[Java] Personal summary of classes and methods (basic)
Summary of ToString behavior with Java and Groovy annotations
Mutual conversion between Java objects and JSON using Moshi