2

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?

3 Answers3

3

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())

cfrick
  • 35,203
  • 6
  • 56
  • 68
2

You can only use Collection::collect like this:

list.collect{it.name}

You can also specify the collector type, for example if you want to use the equivalent of .collect(Collectors.toSet()) you can use:

list.collect(new HashSet(), {it.name})

Groovy demo

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

The scenario looks overcomplicated to me.

If you simply want to re-write java's

list.stream().map(User::getName).collect(Collectors.toList())

into Groovy, you simply get:

list*.name

or (getter)

list*.getName()
injecteer
  • 20,038
  • 4
  • 45
  • 89