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

Patrik Mihalčin :

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

Michael Easter :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465133&siteId=1