Groovy替代Java8的.map()流操作

时间:2017-11-08 16:15:53

标签: java groovy

什么是Groovy替代Java 8的.map()

示例:

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

我正在尝试

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

但我得到List StringtoString()代表而不是代码

1 个答案:

答案 0 :(得分:11)

考虑collect方法,如下所示:

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