how to use iterator in java

‮l.www‬autturi.com
how to use iterator in java

An Iterator is an interface in Java that allows you to iterate over a collection of elements and access their values one at a time. The Iterator interface is part of the Java Collections framework and is implemented by various types of collections, such as List, Set, Queue, and more.

To use an Iterator in a Java program, you can follow these steps:

  1. Obtain an Iterator object for the collection you want to iterate over. You can do this by calling the iterator method of the collection.
List<String> list = Arrays.asList("apple", "banana", "cherry");
Iterator<String> iterator = list.iterator();
  1. Use the hasNext method of the Iterator to check if there are more elements in the collection.
while (iterator.hasNext()) {
    // Process the next element
}
  1. Use the next method of the Iterator to get the next element in the collection.
while (iterator.hasNext()) {
    String element = iterator.next();
    // Process the element
}

In this example, an Iterator object is obtained for a List of strings, and then the Iterator is used to iterate over the elements of the list and access their values one at a time. The hasNext method is used to check if there are more elements in the list, and the next method is used to get the next element.

You can use an Iterator to perform various operations on the elements of a collection, such as processing them, filtering them, or modifying them. The Iterator interface also provides the remove method, which allows you to remove the current element from the collection during the iteration.

Note that the Iterator interface is a generic interface and you need to specify the type of the elements in the collection when you create an Iterator object. You can use the Iterator interface with any collection that implements the Iterable interface, which is the parent interface of the Iterator interface.

Created Time:2017-11-01 22:29:47  Author:lautturi