简体   繁体   中英

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 String s, but toString() representation instead of code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM