{{announcement.body}}
{{announcement.title}}

Groovy Goodness — Java 8 Stream Enhancements [Snippet]

DZone 's Guide to

Groovy Goodness — Java 8 Stream Enhancements [Snippet]

Get groovy with these Java 8 stream enhancements via Groovy 2.5.0!

· Java Zone ·
Free Resource

Groovy 2.5.0 adds several methods to make working with Java 8 Streams more groovy. First, the methods toList and toSet are added to the Stream class. These methods will convert the stream to a List and Set , using the Stream.collect method with Collectors.toList and Collectors.toSet as the argument. Furthermore, we can convert any array object to a Stream using the stream method that is added to all array objects.

In the following example, we use the support of converting an array to a Stream and then getting a List and Set from the stream:

def sample = ['Groovy', 'Gradle', 'Grails', 'Spock'] as String[]

def result = sample.stream()  // Use stream() on array objects
                   .filter { s -> s.startsWith('Gr') }
                   .map { s -> s.toUpperCase() }
                   .toList()  // toList() added to Stream by Groovy

assert result == ['GROOVY', 'GRADLE', 'GRAILS']


def numbers = [1, 2, 3, 1, 4, 2, 5, 6] as int[]

def even = numbers.stream()  // Use stream() on array objects
                  .filter { n -> n % 2 == 0 }
                  .toSet()  // toSet() added to Stream

assert even == [2, 4, 6] as Set


Written with Groovy 2.5.0.

Topics:
groovy, groovy 2.5.0, java, java 8, stream

Published at DZone with permission of Hubert Klein Ikkink , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}