Sunday, July 17, 2022

What is Iterator in Java? Example

Hello guys, if you are wondering what is Iterator in Java and how does it work? when you are supposed to use Iterator and what advantages or disadvantages it provide over other methods of iterating over Java Collections then you have come to the right place. In the past, I have shared how HashMap works in Java and How Garbage collection works and in this article, I am going to share how Iterator works and how they simplify iteration irrespective of different collection types. You all may know about Java collections. It has many lists, maps, etc in it. Now, you may know how to use the inbuilt LinkedList or any other collection, but once that collection is built, how will you iterate over it? I know you all are thinking of loops.


But, what if I told you to do it without the for-each loop?  Think over it for 2 minutes and then we will discuss it. 


What is Iterator in Java? 

 An Iterator is a kind of Java cursor. The Java Iterator interface is used to iterate over a collection of Java object components one by one. Since the Java 1.2 Collection framework, it has been free to use in the Java programming language. It's part of java.util package.

Despite the fact that Java Iterator was introduced in Java 1.2, it is not the oldest mechanism for traversing the components of a Collection object. The Enumerator, which predates Iterator, is the earliest Iterator in the Java programming language. 

The Java Iterator interface replaces the enumerator iterator, which was used in the past to traverse across various accessible collections such as array lists.

Because it can be used with all Collection foundation classes, the Java Iterator is often known as the universal cursor of Java. READ and REMOVE actions are also supported by the Java Iterator. 

When comparing the Java Iterator interface to the enumeration iterator (which was used to traverse legacy collections like vectors) interface, we can say that the names of the available methods in Java Iterator are more precise, easy to understand, and straightforward.

Now, we know what iterator in java is, but how to use them? Don't worry, we will check that out together. Let's see how they are used actually.




How to use Iterator in Java? 

When a user needs the Java Iterator, they must first build an Iterator interface instance from the collection of objects they want to traverse. The receiving Iterator then keeps track of the components in the underlying collection to ensure that the user sees all of the items in the collection.

If a user modifies the underlying collection while traveling through an Iterator that leads to that collection, the Iterator will generally detect and throw an exception the next time the user attempts to get the next component from the Iterator. 

Here is a conceptual view of how Iterator works in Java:

What is Iterator in Java? Example


Let's understand with code with the help of cars




Iterator in Java Code Example

Here is our complete code example for how to use Iterator in Java:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MyIterator {
public static void main(String[] args) {
List<String> list = new ArrayList<>();

list.add("BMW");
list.add("Audi");
list.add("Mercedes");
list.add("Ferrari");
list.add("Bugatti");

Iterator<String> iterator = list.listIterator();

while(iterator.hasNext()) {
System.out.print(iterator.next()+" ");
}
System.out.println("........................");
iterator.remove();

list.forEach(a -> System.out.print(a+" "));
}
}


Output:


How Iterator works in Java


An Iterator is a kind of Java cursor. The Java Iterator interface is used to iterate over a collection of Java object components one by one. 

Now you all must be aware of the basic methods of Iterator and how to use them. Now, Let's see some of it's advantages.

Important points about Iterator and advantages

Due to its various advantages, the iterator in Java has become quite popular. The following are some of the benefits of using a Java Iterator: 
  • These iterators may be applied to any of the Collection framework's classes. 
  • We can utilize both the read and delete actions in a Java Iterator. 
  • If a client is using a for loop, they will be unable to modernize the Collection, while if they are using the Java Iterator, they will be able to do so. 
  • For the Collection API, the Java Iterator is known as the Universal Cursor. 
  • The method identifiers in the Java Iterator are straightforward and straightforward to use.

But, as we saw some of the advantages of Iterator, some of you might be thinking, why don't use for loops (enhanced) and if iterator is there, why need enhanced for loops? Do not worry, we have seen some advantages of Iterator, now let's see some of the disadvantages too :p
every coin has two side.

Disadvantages of iterator

  • Only the forward direction of iteration is preserved by the Java Iterator. To put it another way, the Java Iterator is a one-way iterator. 
  • The Java Iterator does not approve the replacement or expansion of a new component. 
  • The Java Iterator does not retain the different actions such as CREATE and UPDATE in CRUD Operations. 
  • Java Iterator, unlike Spliterator, does not enable traversing elements in the parallel pattern, implying that Java Iterator only offers sequential iteration. 
  • Java Iterator, unlike Spliterator, does not provide more reliable execution while traversing large amounts of data.

That's all about what is Iterator in Java and how you can use it to iterate over different collections in Java. Iterator provides a consistent way to go through each element of a collection irrespective of its type. For example, you can use same way to iterate over List, Set, Stack, Queue or any other Java Collection classes or a user defined class which implements Iterable interface. You can us this consistency to write clean code in Java which works for all kind of collections. 


Related Java Tutorials
If you like this tutorial and wants to learn more about how to convert one data type into another, Please check out the following Java programming tutorials:
  • How to convert String to Double in Java? (example)
  • How to convert char to String in Java? (tutorial)
  • 10 Free Courses to learn Data Structure in Java (free data structure courses)
  • How to convert Enum to String in Java? (example)
  • How to convert float to String in Java? (example)
  • How to convert byte array to String in Java? (program)
  • How to convert double to Long in Java? (program)
  • How to convert ByteBuffer to String in Java? (program)
  • How to convert String to Date in a thread-safe manner? (example)
  • How to convert String to int in Java? (example)
  • How to convert Decimal to Binary in Java? (example)
  • How to parse String into long in Java? (answer)
  • 10 Free Java Courses for Beginners to Join (free Java courses)

Thanks a lot for reading this article so far. If you like this tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.


P. S. - If you are new to the Java world and looking for a free online course to learn Java Programming then you can also join  Java Tutorial for Complete Beginners (FREE) course on Udemy. More than 1.2 million people have joined this course to learn Java online. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.