简体   繁体   中英

How to declare method reference in groovy?

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. Eg 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 (eg 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.

Eg: list.stream().map{ it.name }.collect(Collectors.toList())

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

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

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