This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
If you have some Java code, and you are interested in seeing what it would look like as Groovy code, post it here! If you think want to take a shot at translating it yourself, fire up your groovy console and go for it!
I'll start off with a simple example of reading a file into a String and printing it to stdout.
[ August 31, 2008: Message edited by: Matthew Taylor ]
You could collect all the messages and then print them each.
Or what I like better, split our collection up and then print each group separately.
Joined: Jun 13, 2004
I like your second variation. Those collection operators like "-" are sweet.
Joined: Jun 13, 2004
I've been wanting to do an XML example, but all the Java code that deals with XML is so horrible that I've been putting it off. So I finally decided to omit the Java example, in the hopes that you've probably got some experience with Java XML parsing, and you know just how tedious and nasty it can be.
I'm using the same xml file as my first post's example, and as you can see there is not much involved with the parsing. You just create a new parser and send it the text. Very easy.
And you can see how efficient it is to access the parsed data. The resulting 'catalog' object is a groovy.util.Node. Each node is a collection of Nodes with some nice convenience methods. You can access attributes by using the '@' symbol (the book ids in the printout are from attributes).
Another useful thing I've done is chained a couple of collection methods together to help me format my "England" search results. I first did a 'findAll' with a closure that returns true only if the book description text contains 'England', then I'm calling 'collect' on the results to convert each found Node into a String. This is the same thing as doing this:
Maybe next example will be an XML writer, which is also surprisingly easy. [ September 18, 2008: Message edited by: Matthew Taylor ]