Reputation: 3991
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
Upvotes: 13
Views: 25494
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