Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy alternative of Java8's .map() stream operation

Tags:

java

groovy

What is Groovy's alternative for Java 8's .map()?

Example:

List<String> codes = events
    .stream()
    .map(event -> event.getCode())
    .collect(Collectors.toList());

I was trying to do

events.each { it; return it.getCode() }.collect() as String[]

but I am getting List of Strings, but toString() representation instead of code

like image 255
Patrik Mihalčin Avatar asked Nov 08 '17 16:11

Patrik Mihalčin


People also ask

Can we use Stream in groovy?

Groovy 2.5. 0 and above adds toList and toSet methods as enhancements to Stream. No need to use Collectors.

How do I iterate a map in groovy?

We can iterate through entries using the each() and eachWithIndex() methods. The each() method provides implicit parameters, like entry, key, and value, which correspond to the current Entry. The eachWithIndex() method also provides an index in addition to Entry. Both the methods accept a Closure as an argument.

What does Stream map () operate on?

Stream is an interface and T is the type of stream elements. mapper is a stateless function which is applied to each element and the function returns the new stream. Example 1 : Stream map() function with operation of number * 3 on each element of stream.

Can we convert MAP into Stream?

Converting complete Map<Key, Value> into Stream: This can be done with the help of Map. entrySet() method which returns a Set view of the mappings contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set. stream() method.


1 Answers

Consider the collect method as illustrated below:

class Event {
    def code
    def name
}

def events = []
events << new Event(code: '001', name: 'a')
events << new Event(code: '002', name: 'b')

def codes = events.collect { it.code }

assert ['001','002'] == codes

Note that an equivalent Groovy idiom is the spread-dot operator:

def codes = events*.code
like image 135
Michael Easter Avatar answered Sep 27 '22 18:09

Michael Easter