List Manipulation in Java and Ruby

madlep

After doing a bit of Ruby coding, I get that "this should be easier" feeling when working in Java for any length of time. An example of that is doing some simple operation on a list. In this case, I’m wanting to do something trivial.

The task is simple: given an unsorted list of objects, find the lowest value of some property.

In Java this would look something like:

Date startFoo = null;
for(Foo f : getFoos()) {
  if (startFoo == null) {
    startFoo = f.getStartDate();
  } else {
    startFoo = (startFoo.before(f.getStartDate()) ? startFoo : f.getStartDate());
  }
}

And in Ruby, this would look something like:

get_foos.map{|f| f.start_date}.inject{|low,start| low < start ? low : start}

Not a huge difference in code length or complexity, but once you start needing to do this a few times the extra verbosity starts to add up. All that typing makes it harder to build momentum and get into flow while coding. In any example more complicated than this you’d often have to explicitly handle generic declarations or type casting (which means even more typing). In Ruby you can pretty much think of how it’s going to work, and just run with it (once you grok how map and inject work).

There is a lot of talk about adding closures to Java 7. That’s something I’d love as it would make a lot of the techniques used in Ruby possible in Java. I just hope that it’s done better than when generics were introduced in Java 5. (We’ve just upgraded one of our products from 1.4 to 5, and I’ve been exposed to generics in action for the first time. Not so impressed so far… but that’s another post.)

UPDATE

As pointed out by robert in the comments, there is an even simpler approach:

get_foos.map{|f| f.start_date}.min

Cheers :)


4 Responses to “List Manipulation in Java and Ruby”

  • Robert Says:

    The difference is more striking if you use the built-in function min instead of custom injection:

    get_foos.map{|f| f.start_date}.min

    That’s all you need! :-)

  • Julian Doherty Says:

    Yes, of course :)
    Nice. Cheers robert.
    *slaps head at how obvious it is*

    It’s too easy for someone dumb like me to miss the simpler approach when doing a literal translation like that.

  • Anonymous Says:

    Or in Java:

    startFoo = Collections.min(getFoos);

  • Julian Doherty Says:

    anon - that would work if we wanted to find the minimum Foo object, but this example is looking for the earliest start_date on a foo object.

    The mapping step is the hard part to do in Java.

Leave a Reply