Im trying to use method reference in groovy. And I could not get it working.
The following is working in groovy.
Option2> list.stream().map(user -> user.getName()).collect(Collectors.toList())
What Im trying to achieve?
Option1> list.stream().map(User::getName).collect(Collectors.toList())
The above call is giving following error.
unexpected token: : @ line 33, column 14.
User::getName
1 error
Any suggestions how I can achieve?
The :: shortcut to create a lambda is only supported since Groovy
3.0. With said version your code there should work just fine.
Yet,
what you want to do there has shortcuts already in Groovy for a very
long time. You can use the spread operator *. and it will give you an
ArrayList back. E.g. list*.name is the "groovy" way to write that.
The main difference here is, that this operation is eager. If you need the lazyness of the Java streams (e.g. because your example is simplified), then you can always use a Groovy closure instead of a lambda. There might be need for a cast, but Groovy usually figures this things out quite fine.
E.g.: list.stream().map{ it.name }.collect(Collectors.toList())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With