Looping through Collections is fun in Java 5

Edit: This post was earlier titled “Looping through Collections is fun in Java 6” which has now been renamed to “Looping through Collections is fun in Java 5” due to the accidental discrepancy of mentioning the feature belonging to Java 6. The mistake is rectified. Thanks for the feedback to all.

The traditional looping for construct has served well for many years in Java. Even today, for collections people still use the traditional approach for looping through them. The simple reason being familiarity. Its evident that the powers provided by the revolutionary addition of features in Java upgrades have yet to see their complete establishment.

Coming to the collections frameworks the other leagues of languages like PHP, JavaScript, VB have provided convenient looping constructs for the for syntax namely the for each block. Java programmers have craved long for the same and its time that it was implemented in the favorite language of millions worldwide.

The collections framework comes with a new for construct or the for-each block although the each term is missing from the syntax. Now you don’t need the much abused Iterator for looping and fretting over the same routines to be written when a collection is received. The for-each block makes it more cooler to write the same construct without the need to obtain an Iterator and with the added feature of generics, you don’t have to typecast the object received from the collection.

The earlier way in which the code for looping through a collection would have been written as,

	List list = new ArrayList();
	String a = "Hello";
	String b = "World";
	list.add(a);
	list.add(b);
 
	String s;
	for(Iterator i = list.iterator(); i.hasNext();){
		s = (String) i.next();
		System.out.print(s + " ");
	}

OR

	Iterator i = list.iterator();
	String s;
	while(i.hasNext()){
		s = (String) i.next();
		System.out.print(s + " ");
	}

The result would print “Hello World”.

The Iterator becomes simply unnecessary since it is obvious that a collections require it to get looped. But in the traditional approach the programmer has to make the trouble of introducing it every time he sees a collection. In Java 5 you would be writing the same block as follows:

	List<String> list = new ArrayList<String>();
	String a = "Hello";
	String b = "World";
	list.add(a);
	list.add(b);
 
	for(String s : list)
		System.out.print(s + " ");

Here you see that looping through the for-each block is so simple that it reduces all the need to construct an Iterator. The generics features make the collections specific to one type of object i.e when you define List<String> you make it explicit that the List would only contain String objects. Of course you would question about losing flexibility by doing this. But generics is a very vast topic to be dealt with and it includes all the features for introducing objects of inheritance in a collection.

Coming down to the main topic i.e the for-each construct, here you only have to define the type of object which you will be requiring in your loop. In the example I had made a String collection. So the object I would require to store the intermediate values would be a String object. The object “s” of String type does this work of storing the intermediate values.

The syntax “String s : list” means that “for each object of type String in the collection list, do loop and store the obtained value in s“. Once inside the loop you get the intermediate value in s to be printed. Hence avoiding the need of an Iterator and a type cast for looping inside the new collections framework. Using this feature the code definitely becomes more easier to be written, debug, test and mainly readable.

8 thoughts on “Looping through Collections is fun in Java 5

  1. You can do more (ominous sound) you can make a custom iterator that implements iterable, and then you can use that iterator in the for each loop. That means you can make a “lazy list” that produces values on iteration. Of course you loose the index effect in a real lazy list, but that is really cool anyway

  2. @paulo – What is the purpose of of making a custom iterator? Could you please elaborate on the aspect you have stated.

    @craig – yes I have mentioned that it was introduced in Java 5 but its use with generics is more easier to be worked upon in Java 6.

  3. Everything you mention in the article was already available in Java 5, including generics support and Iterable (custom iterators). Where I work, we have been using these features for years.

    I’ve played a bit with Java 6, but haven’t noticed any changes in this area. What specifically has been added? I’d be curious to know, as there are currently some glaring annoyances with Java 5, like the fact that Iterators aren’t themselves Iterable, making looping over them more complicated than necessary.

  4. @craig – I think I jumped on the bandwagon quite a bit late. I had not explored Java for a long time and I just mistook the features offered through the collections framework were of Java 6. But I have still seen people around me use the age old technique of using the Iterator and absorbed the for-each block as a feature of Java 6 since I use the JDK 1.6 api’s.

    This post should have been of Java 5 instead of Java 6. Thanks for the clarification.

  5. Not a problem… I’m actually a bit disappointed as I was hoping there actually were some improvements in Java 6 in this regard.

    Good article regardless.

  6. Hi Craig,

    I saw your site randomcoder.com. Could you please tell me something about it. What’s your objective in it?
    Just was curious to know.

  7. I’ve been developing in Java for about 10 years now, and it seems I’m always re-writing the same code again and again. So I’ve decided that this time around I’m going to do it right…

    randomCoder is an experiment of mine. It’s an open-ended site that contains tutorials and best practices on how to get common things done in Java EE development. In addition, all the code in use on the site is under a BSD license so that hopefully, not only do I not have to reinvent the wheel, but others won’t have to either.

    I’ve also posted some libraries that I’ve written, including some common JSP taglibs and a J2EE security replacement. All of it is open-sourced, and available through Subversion.

Leave a Reply

Your email address will not be published. Required fields are marked *