Java for iterator example

Java Iterator

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an «iterator» because «iterating» is the technical term for looping.

To use an Iterator, you must import it from the java.util package.

Getting an Iterator

The iterator() method can be used to get an Iterator for any collection:

Example

// Import the ArrayList class and the Iterator class import java.util.ArrayList; import java.util.Iterator; public class Main < public static void main(String[] args) < // Make a collection ArrayListcars = new ArrayList(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); // Get the iterator Iterator it = cars.iterator(); // Print the first item System.out.println(it.next()); > > 

Looping Through a Collection

To loop through a collection, use the hasNext() and next() methods of the Iterator :

Example

Removing Items from a Collection

Iterators are designed to easily change the collections that they loop through. The remove() method can remove items from a collection while looping.

Example

Use an iterator to remove numbers less than 10 from a collection:

import java.util.ArrayList; import java.util.Iterator; public class Main < public static void main(String[] args) < ArrayListnumbers = new ArrayList(); numbers.add(12); numbers.add(8); numbers.add(2); numbers.add(23); Iterator it = numbers.iterator(); while(it.hasNext()) < Integer i = it.next(); if(i < 10) < it.remove(); >> System.out.println(numbers); > >

Note: Trying to remove items using a for loop or a for-each loop would not work correctly because the collection is changing size at the same time that the code is trying to loop.

Читайте также:  Питон почему не работает

Источник

Java Iterator with examples

Iterator is used for iterating (looping) various collection classes such as HashMap, ArrayList, LinkedList etc. In this tutorial, we will learn what is iterator, how to use it and what are the issues that can come up while using it. Iterator took place of Enumeration, which was used to iterate legacy classes such as Vector. We will also see the differences between Iterator and Enumeration in this tutorial.

Iterator without Generics Example

Generics got introduced in Java 5. Before that there were no concept of Generics. Refer this guide to learn more about generics: Java Generics Tutorial.

import java.util.ArrayList; import java.util.Iterator; public class IteratorDemo1 < public static void main(String args[])< ArrayList names = new ArrayList(); names.add("Chaitanya"); names.add("Steve"); names.add("Jack"); Iterator it = names.iterator(); while(it.hasNext()) < String obj = (String)it.next(); System.out.println(obj); >> >

In the above example we have iterated ArrayList without using Generics. Program ran fine without any issues, however there may be a possibility of ClassCastException if you don’t use Generics (we will see this in next section).

Iterator with Generics Example

In the above section we discussed about ClassCastException. Lets see what is it and why it occurs when we don’t use Generics.

import java.util.ArrayList; import java.util.Iterator; public class IteratorDemo2 < public static void main(String args[])< ArrayList names = new ArrayList(); names.add("Chaitanya"); names.add("Steve"); names.add("Jack"); //Adding Integer value to String ArrayList names.add(new Integer(10)); Iterator it = names.iterator(); while(it.hasNext()) < String obj = (String)it.next(); System.out.println(obj); >> >
ChaitanyaException in thread "main" Steve Jack java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at beginnersbook.com.Details.main(Details.java:18)

In the above program we tried to add Integer value to the ArrayList of String but we didn’t get any compile time error because we didn’t use Generics. However since we type casted the integer value to String in the while loop, we got ClassCastException.

Use Generics:
Here we are using Generics so we didn’t type caste the output. If you try to add a integer value to ArrayList in the below program, you would get compile time error. This way we can avoid ClassCastException.

import java.util.ArrayList; import java.util.Iterator; public class IteratorDemo3 < public static void main(String args[])< ArrayListnames = new ArrayList(); names.add("Chaitanya"); names.add("Steve"); names.add("Jack"); Iterator it = names.iterator(); while(it.hasNext()) < String obj = it.next(); System.out.println(obj); >> >

Note: We did not type cast iterator returned value[it.next()] as it is not required when using Generics.

Java Iterator Methods

It returns true, if there is an element available to be read. In other words, if iteration has remaining elements.

It returns the next element in the iteration. It throws NoSuchElementException , if there is no next element available in iteration. This is why we use along with hasNext() method, which checks if there are remaining elements in the iteration, this make sure that we don’t encounter NoSuchElementException .

It removes the last element returned by the Iterator, however this can only be called once per next() call.

4. forEachRemaining():

default void forEachRemaining(Consumer action)

Performs the specified action on all the remaining elements.

Iterating HashMap using Iterator

import java.util.*; class JavaExample < public static void main(String[] args) < HashMaphm = new HashMap(); hm.put("Apple", 100); hm.put("Orange", 75); hm.put("Banana", 30); System.out.println("HashMap elements: " + hm); // Getting an iterator Iterator hmIterator = hm.entrySet().iterator(); while (hmIterator.hasNext()) < Map.Entry mapElement = (Map.Entry)hmIterator.next(); int price = (int)mapElement.getValue(); System.out.println(mapElement.getKey() + " , " + price); >> >

Java Iterator Example Output

Difference between Iterator and Enumeration

An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:
1) Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
2) Method names have been improved. hashNext() method of iterator replaced hasMoreElements() method of enumeration, similarly next() replaced nextElement().

Advantages of Iterator

  • While iterating a collection class using loops, it is not possible to update the collection. However, if you are iterating a collection using iterator, you can modify the collection using remove() method, which removes the last element returned by iterator.
  • The iterator is specifically designed for collection classes so it works well for all the classes in collection framework.
  • Java iterator has some very useful methods, which are easy to remember and use.

Disadvantages of Iterator

  • It is unidirectional, which means you cant iterate a collection backwards.
  • You can remove the element using iterator, however you cannot add an element during iteration.
  • Unlike ListIterator which is used only for the classes extending List Interface, the iterator class works for all the collection classes.

ConcurrentModificationException while using Iterator

import java.util.ArrayList; public class ExceptionDemo < public static void main(String args[])< ArrayListbooks = new ArrayList(); books.add("C"); books.add("Java"); books.add("Cobol"); for(String obj : books) < System.out.println(obj); //We are adding element while iterating list books.add("C++"); >> >
C Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source) at beginnersbook.com.Details.main(Details.java:12)

We cannot add or remove elements to the collection while using iterator over it.

Explanation From Javadoc:
This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.
For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

i think while we can remove the element from the collection only we cannot add the element into the collection it will throw concurrentmodificationexception

Источник

How to iterate through Java List? Seven (7) ways to Iterate Through Loop in Java

How to iterate through Java List? Seven (7) different ways to Iterate Through Loop in Java

How to iterate through Java List? This tutorial demonstrates the use of ArrayList, Iterator and a List.

There are 7 ways you can iterate through List.

  1. Simple For loop
  2. Enhanced For loop
  3. Iterator
  4. ListIterator
  5. While loop
  6. Iterable.forEach() util
  7. Stream.forEach() util

Java Example:

You need JDK 13 to run below program as point-5 above uses stream() util.

void java.util.stream.Stream.forEach (Consumer action) p erforms an action for each element of this stream.

package crunchify.com.tutorials; import java.util.*; /** * @author Crunchify.com * How to iterate through Java List? Seven (7) ways to Iterate Through Loop in Java. * 1. Simple For loop * 2. Enhanced For loop * 3. Iterator * 4. ListIterator * 5. While loop * 6. Iterable.forEach() util * 7. Stream.forEach() util */ public class CrunchifyIterateThroughList < public static void main(String[] argv) < // create list ListcrunchifyList = new ArrayList(); // add 4 different values to list crunchifyList.add("Facebook"); crunchifyList.add("Paypal"); crunchifyList.add("Google"); crunchifyList.add("Yahoo"); // Other way to define list is - we will not use this list :) List crunchifyListNew = Arrays.asList("Facebook", "Paypal", "Google", "Yahoo"); // Simple For loop System.out.println("==============> 1. Simple For loop Example."); for (int i = 0; i < crunchifyList.size(); i++) < System.out.println(crunchifyList.get(i)); >// New Enhanced For loop System.out.println("\n==============> 2. New Enhanced For loop Example.."); for (String temp : crunchifyList) < System.out.println(temp); >// Iterator - Returns an iterator over the elements in this list in proper sequence. System.out.println("\n==============> 3. Iterator Example. "); Iterator crunchifyIterator = crunchifyList.iterator(); while (crunchifyIterator.hasNext()) < System.out.println(crunchifyIterator.next()); >// ListIterator - traverse a list of elements in either forward or backward order // An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, // and obtain the iterator's current position in the list. System.out.println("\n==============> 4. ListIterator Example. "); ListIterator crunchifyListIterator = crunchifyList.listIterator(); while (crunchifyListIterator.hasNext()) < System.out.println(crunchifyListIterator.next()); >// while loop System.out.println("\n==============> 5. While Loop Example. "); int i = 0; while (i < crunchifyList.size()) < System.out.println(crunchifyList.get(i)); i++; >// Iterable.forEach() util: Returns a sequential Stream with this collection as its source System.out.println("\n==============> 6. Iterable.forEach() Example. "); crunchifyList.forEach((temp) -> < System.out.println(temp); >); // collection Stream.forEach() util: Returns a sequential Stream with this collection as its source System.out.println("\n==============> 7. Stream.forEach() Example. "); crunchifyList.stream().forEach((crunchifyTemp) -> System.out.println(crunchifyTemp)); > >

Output:

==============> 1. Simple For loop Example. Facebook Paypal Google Yahoo ==============> 2. New Enhanced For loop Example.. Facebook Paypal Google Yahoo ==============> 3. Iterator Example. Facebook Paypal Google Yahoo ==============> 4. ListIterator Example. Facebook Paypal Google Yahoo ==============> 5. While Loop Example. Facebook Paypal Google Yahoo ==============> 6. Iterable.forEach() Example. Facebook Paypal Google Yahoo ==============> 7. Stream.forEach() Example. Facebook Paypal Google Yahoo Process finished with exit code 0

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

Источник

Оцените статью