What Java foreach loop can do?

Foreach is one of new features introduced in Java 5. I simply love this feature because it provides simplicity and readability and reduces the code. It is more powerful when used with generics (another feature added in Java 5). Lets check out basic syntax of foreach loop and compare it with traditional for loop.

//Traditional For Loop Syntax:

String []strings = {”For”, “each” , “loop”, “rocks”};

for (int i=0; i<strings.size(); ++i)
{
    String s = (String) strings.get(i);
    System.out.println(s);
}

//Foreach Loop Sytax:

String []strings = {”For”, “each” , “loop”, “rocks”};

for (String s : strings)
{
    System.out.println(s);
}

Many developer think of Java foreach loop, is something like “foreach x in myList” but that is not the case. The same for keyword is used as shown in above code snippet. When you see a colon (:) read it as in. The loop above reads as for each String s in strings.

Lets take another example that uses generics and compare them with old for loop syntax. Java generics saves us from the burdon of type casting.

public class MyClass
{
    String type = "MyClass";
    int id = 10;
    public String getType(){return type;}
    public void setType(String type){this.type = type;}
    public int getId(){return id;}
    public void setId(int id){this.id = id;}
}

//Traditional For Loop Syntax:

ArrayList<MyClass> myObjects = getMyClassObjects(); //function returns an array list with myClass objects
MyClass myClass;
for (int i=0; i < myObjects.size(); i++)
{
    myClass = myObjects.get(i);
    //do something like
    myClass.getType();
    myClass.getId();
}

//another way using iterator
for(Iterator<MyClass> itr = myObjects.iterator(); itr.hasNext();)
{
    //do something like
    itr.next().getType();
    itr.next().getId();
}

//Foreach Loop Sytax:

ArrayList<MyClass> myObjects = getMyClassObjects(); //function returns an array list with myClass objects
for(MyClass myClass: myObjects)
{
    //do something like myType.getType();
    myClass.getType();
    myClass.getId();
}

As you can see, the foreach construct combines beautifully with generics. It preserves all of the type safety, while removing the remaining clutter. Because you don’t have to declare the iterator, you don’t have to provide a generic declaration for it. (The compiler does this for you behind your back, but you need not concern yourself with it.)

HashMap traversing was never so easy before foreach introduction, this is one the best uses of for each loop.

//Traditional For Loop Syntax:

HashMap m = new HashMap();
//code for filling the map
Iterator it = m.keySet().iterator();
while (it.hasNext()) {
    String key = (String) it.next();
    String value = (Vector) m.get(key);
}

//Foreach Loop Sytax:

HashMap m = new HashMap();
//code for filling the map
for (String key : m.keySet()) {
    Object value = m.get(key);
}

The foreach loop provides a simple, consistent solution for iterating arrays, collection classes, and even your own collections. It eliminates much of the repetitive code that you would otherwise require. The foreach loop eliminates the need for casting as well as some potential problems. The foreach loop is a nice new addition to Java that was long overdue. If you want to share your experience with me and other readers, please drop a comment.


No Comments! Be The First!

Leave a Reply

You must be logged in to post a comment.