If this is my class:
class Something
{
UUID id;
// Other members
}
Given a List<Something> things
and I want to get a List<UUID> ids
, this is what I usually do:
List<UUID> ids = new ArrayList<UUID>
for(Something thing : things)
{
ids.add(thing.getId());
}
return ids;
Is there a more elegant way of doing this in Java 6?
[I googled for this pattern, however, didn't find much as I think I lacked the right keywords]
2 Answers 2
When I have encountered this type of problem, it typically involves creating some ugly code in your method to do that iteration. In essense, there is no way to do things any differently, you have to iterate, and collect the UUID's (but, you could wait for Java8 and do lambdas ..).
But, there is no reason why you have to do it outside of the Something
class. A trick you can do which keeps like-code together, is to put a static method on Something
, which does:
public static final List<UUID> getUUIDs(Iterable<Something> somethings) {
List<UUID> ids = new ArrayList<UUID>();
for(Something thing : somethings) {
ids.add(thing.getId());
}
return ids;
}
Now that code is stashed away somewhere useful, and when you need it you can:
for (UUID uuid : Something.getUUIDs(things) {
... do something ....
}
-
\$\begingroup\$ Yes, once the world (Read : my org) is ready to adopt Java 8, better code will be seen. \$\endgroup\$TJ-– TJ-2014年02月26日 08:01:17 +00:00Commented Feb 26, 2014 at 8:01
You can do it with Guava's Function
and Lists
(Functional idioms in Guava, explained):
Function<Something, UUID> getIdFunction = new Function<Something, UUID>() {
public UUID apply(Something input) {
return input.getId();
}
};
List<UUID> ids2 = Lists.transform(things, getIdFunction);
(If you're unable to include a 3rd party library to your project for any reason you still can copy the code of relevant classes or create your own implementation with the same pattern.)