Paid By the Keystroke?

by Charles Miller on September 24, 2003

On Monday evening, I did a bit of Ruby hacking. On Tuesday morning, I arrived at work and my first task involved iterating through a list, and doing something to each of its elements. My fingers were already typing list.each, and I had to wrench my brain from my Ruby mindset back to the Java Way.

Some time later in the day, I read Philip Greenspun's much-linked Java-is-an-SUV flame.

Problem: I have a list of objects. I want to create another list containing the ‘id’ property of those objects.

Solutions:1

Ruby
list.map { |i| i.id }
Perl
map { $_->id } @list;
Python
[x.id for x in list]
Common Lisp (Corrected by Andreas)
(mapcar #'id list)
Smalltalk (from James)
list collect: [:each | each id]
OGNL (from Jason)
list.{id}
Java
List ids = new ArrayList();
for (Iterator i = list.iterator(); i.hasNext(); ) {
    ids.add(new Long(((Thingy)i.next()).getId()));
}
Java w/ 1.5-style Generics/For Loop/Autoboxing
List<Long> ids = new ArrayList<Long>();
for (Thingy x :list) ids.add(x.getId());
Java w/ Commons-Collections (from Chris)
Collection ids = CollectionUtils.collect(
     x, new Transformer() {
            public Object transform( Object thingy ) {
                return ((Thingy)thingy).getId();
            }
        });

1 I was too lazy to test that they work, but the syntax is close enough. Bug reports to /dev/null.

Previously: Music Consumption

Next: Introducing: Dysfunctional Programming