Elegant way of making a List of an attribute from a list of objects containing that attribute If this is my class:

class Something
{
    UUID id;
    // Other members
}


Given a List&lt;Something&gt; things and I want to get a List&lt;UUID&gt; ids, this is what I usually do:

List&lt;UUID&gt; ids = new ArrayList&lt;UUID&gt;
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]
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&lt;UUID&gt; getUUIDs(Iterable&lt;Something&gt; somethings) {
    List&lt;UUID&gt; ids = new ArrayList&lt;UUID&gt;();
    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 ....
}