How to loop through Collection

To loop through a collection in java we have 2 options:

1. loop using iterator:

        Iterator<string> iterator = myCollection.iterator();
        while (iterator.hasNext()) {
        System.out.println("value=" + iterator.next());
        }

2. loop using for-each:

        for (String str : myCollection) {
        System.out.println("value=" + str);
        }

Leave a Reply