Native collections are Groovy, man

Hip languages like Ruby, Python, and Groovy (to name a few) are unique in that they make collections (i.e. lists and maps) a part of the syntax of the language. This is distinctly different than Java, C#, and C++, which as you well know, require that you use a collection library. Both options have their pros and cons– a great example of innovation was Doug Lea’s concurrent library for Java, which, because it was his bag, provided a series of enhanced collection objects until they were finally incorporated into J2SE 5.0. But making collections (and their handling) native to a language has its benefits as well.

For example, if I need to create a list of Strings in Java, I’d have to do something like:

Collection<String> coll = new ArrayList<String>();
coll.add("Leesburg");
coll.add("Reston");
coll.add("Herndon");
coll.add("Mclean");

I’d also have to import both Collection and ArrayList. If I’d like to now iterate over this collection of 4 Strings, I have to do two things:

  • Obtain a handle to an Iterator
  • Iterate over the collection via a looping mechanism, like a for or while loop

With my Collection object from above, using these two steps, I could use a for loop as follows:

for(Iterator iter = coll.iterator(); iter.hasNext();){
 String value = (String)iter.next();
 System.out.println(value);
}

When collections are natively available, their usage becomes quite hip. For example, in Groovy, if I’d like to create a list of Strings, I can do something like:

def coll = ["Leesburg","Reston","Herndon"]

In fact, adding another item to the list of 3 Strings doesn’t even require a call to the add method– Groovy has overloaded the << operator to mimic add like so:

coll << "Mclean" 

What’s particularly interesting, man, is that the coll object is still a valid Java Collection object– in fact, it’s of type ArrayList (just like the Java code from earlier).

assert coll.class == ArrayList.class

Iteration is also a breeze with languages that support native collections. In Groovy, the bogue Iterator object, so familiar in Java, basically disappears along with traditional looping constructs too:

coll.each{
 println it
}

Note the code above produces the exact same result as the same copasetic for loop in Java from earlier.

Languages like Groovy, Ruby, etc, are in truth, general purpose languages (just like Java’s bag) but are particularly suited to building applications rapidly because, among other things, they offer syntactic sugar that makes everyday programming tasks easier. Plus, what’s seriously appealing about Groovy is that this rapidness is 100% compatible with existing Java code. Can you dig it?

Related odds and ends
 

11 Responses to “Native collections are Groovy, man”

  1. on 13 Jun 2007 at 2:11 am L-Dog

    Don’t forget that in Java you can also do:

    Collection = Arrays.asList(”one”, “two”, “three”);

  2. on 13 Jun 2007 at 2:51 am Andy

    L-Dog- right on! That’s much easier than repetitively calling add. Thanks for pointing that out!

  3. on 13 Jun 2007 at 7:16 am Stephan Schmidt

    What astonishes me is the fixation of many people on collection sugar. When looking back at my long Java development history, I can’t remember an instance where I needed to create a collection of Strings. Either the data comes from the database, from a config file or the data comes from the user. But usually never from the application. Most of the time the developer only inititializes an empty list, like in List customers = []; which is only marginally shorter than List customers = new ArrayList();

    @Andy: Do you have real examples of initializing lists with data in an application?

    As a sidenote: for (String value: collection) { sout( value ) } is probably shorter than your iterator example :-)

    (I like Groovy a lot :-) The Groovy syntax though is helpful for unit testing, see below. A clever IDE (like IDEA) perhaps could just show you [] instead of ArrayList and only show ArrayList as a tooltip. And it could also hide the generic information for more readability.

    @L-Dog: Excellent. This is the exception to the rule, I’ve been using your construct quite often for JUnit tests, where this is handy to create test data.

  4. on 13 Jun 2007 at 7:22 am Andy

    Stephan-

    You raise a great point– I really wrote that code to demonstrate iteration, not so much as an example of creating collections. I agree– I rarely do this in practice too!

  5. on 13 Jun 2007 at 5:16 pm afsina

    for(Iterator iter = coll.iterator(); iter.hasNext();){
    String value = (String)iter.next();
    System.out.println(value);
    }

    can also be written as

    for(String s : coll )
    System.out.println(s);

    Although i agree that Java should have some more helpers for Collections (not necessarily ‘in’ the language syntax), you don’t have to show Java code unnecessarily verbose.

  6. on 13 Jun 2007 at 6:50 pm Andy

    Yep, you are 100% on, man. The new for loop in Java does make iteration much, much easier. Thanks for calling me on that. :)

  7. on 13 Jun 2007 at 7:04 pm Andy

    As a side note, this posting was bound to get some great thoughts and other view points as I learned long ago when starting to write Groovy & Java comparisons– for some excellent points check out these threads:
    Groovy making good progress and Practically Groovy: Get Groovy with JDBC programming both of which appeared on TheServerSide in 2005.

    One of my favorite comments related to some Java I wrote and compared to Groovy: “If that is your ‘normal’ Java, no wonder you like Groovy. But I can say in all honesty, if someone came up to me using this as a selling point of Groovy, I’ll laugh them out the door.” And he’s got a valid point too. Groovy has a number of selling points, but something to keep in mind– Groovy also obeys the 80/20 rule– it is more concise and easier to write for roughly 80% of the code you normally write in Java or it is easier and more concise for roughly 80% of the people who write Java…

  8. on 14 Jun 2007 at 2:09 am Pablo

    I think that the power of Groovy does not lie so much on it’s sintactic sugar, but on the power it has no wrap up some complex Java APIs. The first thing that comes into my mind is JMX:

    Java:
    println server.getAttribute(beanName, ‘Age’)
    server.setAttribute(beanName, new Attribute(’Name’, ‘New name’))
    Object[] params = [5, 20]
    String[] signature = [Integer.TYPE, Integer.TYPE]
    println server.invoke(beanName, ‘add’, params, signature)

    Groovy:
    def mbean = new GroovyMBean(server, beanName)
    println mbean.Age
    mbean.Name = ‘New name’
    println mbean.add(5, 20)

    That kind of things are the ones that are useful for me.

    JM2C.

  9. on 14 Jun 2007 at 2:23 pm Andy

    Pablo- I couldn’t agree more with you! I had an interesting experience using the Cargo framework in Groovy first and then having to port some of it to a Java based implementation for a particular client and I found myself amazed on how easy it was to get things working in Groovy (as opposed to Java) due to its relaxed nature.

  10. on 15 Jun 2007 at 9:13 pm Glen Pepicelli

    If you look at some idiomatic Perl scripts you will see collections used almost every line. So it definately opens up a new style of programming.

    What I really like about Groovy is that your can swap out the default implementations of the list and maps with any class that extends those interfaces– really cool.

    Glen

  11. on 18 Jun 2007 at 8:18 am Redsolo

    What I love with python is the support for “-1″. There are so many times I have to do collection.getLength() or collection.getSize() only to get the index of the last item.

    With python you can only do:
    lastItem = collection[-1]

    It is also so easy to get a subset of a collection:
    subset = collection[1:-1]

    This is what they should bring into the next release of java!

Trackback this Post | Feed on comments to this Post

Leave a Reply