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...
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.
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