Emulating Ruby’s Enumerable in Java

An unfortunate fact of my career is that I still do a lot of consulting work in Java. I developed my sour disposition, as many others before me have, by learning Ruby. One of the features I miss the most in Java land is Ruby’s succinct way of dealing with iteration. For instance, if I wanted to find all the elements in an array of strings containing the word foo I could do:

foos = strings.select {|e| e.match /foo/}

The simple form in Java would require four lines:

List foos = new ArrayList();
for(String e : strings) {
    if(e.contains(“foo”))  foos.add(e);
}

So, I thought, what would be the most succinct way I could implement closures in Java right now? Anonymous classes came to mind, but they’re incredibly verbose for simple operations like the example above. I let the thought percolate a few days which eventually lead me to the beanshell scripting framework. With a little bit of work I was able to allow following in Java:

List foos = rubyCollection.select(“e.contains(\”Foo\”)”);

Beanshell lets you invoke arbitrary snippets of Java at runtime and provide a context for that execution. I was pretty elated with my work until I ventured into some simple performance tests. My first implementation was about 782 times slower than the natural Java version for a 500,000 element list. That killed my buzz. I read up a bit on beanshell and optimized the algorithm down to ~100 times worse than the performance of Java, still far insufficient.

Beanshell is just too slow. I need a parser that can cache an expression, then evaluate it over and over again with different context. If I could, I’d like to do the following in BeanShell:

Interpreter i = new Interpreter();
i.parse(expression);
i.set(“e”, element);
i.eval();
i.set(“e”, element);
i.eval();

I’m going to run through the rest of the Enumerable methods using my current scheme just for fun. Once I’m happy with it I’ll post the code. Maybe someone smarter than I can pick it up where I left off.
Can anyone point me to a parser that will support my needs?

Leave a Reply