Techoceanhub logo

Iterators and foreach loop

In Java, iterators and the foreach loop (also known as enhanced for loop) are used to traverse or iterate over collections such as arrays, lists, sets, and maps. They provide a convenient way to access and process each element of a collection without the need for explicit index management.

Iterators: An iterator is an object that allows you to iterate over the elements of a collection one by one. It provides methods to check if there are more elements in the collection, retrieve the next element, and remove elements if necessary. Here’s an example of using an iterator:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
    String name = iterator.next();
    System.out.println(name);
}

In this example, we create an iterator for the names list and use a while loop to iterate over the elements. The hasNext() method checks if there are more elements, and the next() method retrieves the next element.

Foreach Loop: The foreach loop (enhanced for loop) is a simplified way to iterate over elements of a collection. It automatically manages the iteration process and eliminates the need for explicit iterator handling. Here’s an example:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

for (String name : names) {
    System.out.println(name);
}

In this example, we use the foreach loop to iterate over the names list. The loop automatically retrieves each element and assigns it to the name variable for processing.

Both iterators and the foreach loop provide a convenient way to iterate over collections in Java. However, it’s important to note that iterators allow you to modify the collection while iterating, whereas the foreach loop does not support modification during iteration.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .