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.


Ruby { |i| }
map { $_->id } @list;
[ for x in list]
Common Lisp (Corrected by Andreas)
(mapcar #'id list)
Smalltalk (from James)
list collect: [:each | each id]
OGNL (from Jason)
List ids = new ArrayList();
for (Iterator i = list.iterator(); i.hasNext(); ) {
    ids.add(new Long(((Thingy);
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