Samstag, 4. Juni 2011

Convert a CSV File in Groovy, Java or Scala?

Last week I have simple task I must convert a simple CSV file into another CSV format. My first solution was a simple Groovy script. Then inforw sends me a Java solution, to show me that with Java it is no much more code then the Groovy implementation is. Today I wrote just for fun a solution in Scala, to see how the code looks in Scala. My favorite of the three implementations is at the moment the Groovy one. But I think the Scala implementation has the best readability. Below you see the three implementations.

I'm curious what you like, feel free for comments? And I would be glad if someone contributes even further implementation in Clojure, Python, Perl,… or even a better Scala, Java or Groovy implementation.

The Groovy Implementation:

The Java Implementation:

The Scala Implementation:

Thanks @inforw for the discussion and the Java implementation.


  1. Here's the Python version for completeness, if you promise not to call it 'Phyton' anymore. :P

    A few notes, I think the rest is self-explanatory (it's Python, after all!):

    • I followed the Groovy output pattern, because I didn't understand the Java and Scala versions (aren't they referring to six fields, even though there are only five?).

    • The 'with' statement works like C#'s 'using' or a 'finally' block in Java. It makes sure close() is invoked on the context manager object (in this case a file), whether an exception is raised or the block terminates regularly.

    • The csv.reader() method returns a reader object, which is also an iterator. That's why you can just for-loop over it. Each invocation of the iterator returns a list, which is unpacked into individual variables by the statement following the 'for'.

    • The firstname/lastname concatenation is done using the %-operator purely for demonstrational purposes. In this case, a regular concatenation would actually be easier to read: "firstname + ' ' + lastname".

  2. Oh thx for the typo hint I fixed Phyton to Python ... and thx a lot for the Python implementation...