Patrik Mihalčin
Patrik Mihalčin

Reputation: 3991

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

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

Upvotes: 13

Views: 25494

Answers (1)

Michael Easter
Michael Easter

Reputation: 24468

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

Upvotes: 32

Related Questions