Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect property of objects in collection

In C# I can do this:

IEnumerable<long> ids = things.select(x => x.Id);

In Java I have to do this:

Collection<Long> ids = new ArrayList<Long>(things.size());
for(Thing x : things)
   ids.add(x.getId());

Have to do this sort of thing quite a lot now and wonder if there is a more generic way to do this in Java. Could create a method to do it, but then I would have to add an interface with the getId method or something like that... which I can't...

like image 203
Svish Avatar asked Nov 21 '11 10:11

Svish


1 Answers

using Guava, specifically the function interface :

public class ThingFunction implements Function<Thing, Long> {
    @Override
    public Long apply(Thing thing) {
        return user.getId();
    }
} 

and invoked like this (where transform is a static import from Collections2 of guava:

Collection<Long> ids = transform(things, new ThingFunction());

Guava has quite a few other benefits too.

like image 158
NimChimpsky Avatar answered Oct 02 '22 17:10

NimChimpsky