3
\$\begingroup\$

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]

asked Feb 26, 2014 at 6:33
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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 ....
}
answered Feb 26, 2014 at 6:53
\$\endgroup\$
1
  • \$\begingroup\$ Yes, once the world (Read : my org) is ready to adopt Java 8, better code will be seen. \$\endgroup\$ Commented Feb 26, 2014 at 8:01
1
\$\begingroup\$

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

Landei
7,0422 gold badges25 silver badges34 bronze badges
answered Feb 26, 2014 at 7:23
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.