{"id":1194,"date":"2016-03-21T06:42:22","date_gmt":"2016-03-21T06:42:22","guid":{"rendered":"http:\/\/abhiandroid.com\/java\/?page_id=1194"},"modified":"2016-03-21T08:12:57","modified_gmt":"2016-03-21T08:12:57","slug":"iterator","status":"publish","type":"page","link":"https:\/\/abhiandroid.com\/java\/iterator","title":{"rendered":"Iterator In Java With Example"},"content":{"rendered":"<p>There are different ways by which we can traverse over elements that are for-loop, while loop, do-while, for each loop\u00a0etc. They all are index based on traversing methods. But as we know Java is purely\u00a0object oriented\u00a0 programming language in which we always have possible ways of doing things using objects. So\u00a0Iterator\u00a0is a way to traverse the data over the collection objects.<\/p>\n<p>Java Iterator\u00a0is an Interface that belongs to the collection framework allow us to traverse the collection objects and access the elements of \u00a0that collection. Basically List Interface and Set Interface provides the iterator. Iterator can be used with all the implementation of Set and List Interfaces like for example\u00a0ArrayList,\u00a0LinkedList,\u00a0 TreeSet etc.<\/p>\n<p>Map implementation such as\u00a0HashMap, TreeMap, LinkedHashMap doesn\u2019t provide Iterator directly but we can iterate over them by getting there key-Set or Value Set.<\/p>\n<hr \/>\n<h4><strong>Methods of Iterator<\/strong><\/h4>\n<p><strong><span style=\"color: #008000;\">1. boolean hasNext( )<\/span> <\/strong><\/p>\n<p>This method returns true if there are more elements else it returns false.<\/p>\n<p><span style=\"color: #008000;\"><strong>2. Object next( )<\/strong><\/span><\/p>\n<p>This method returns the next element in the collection or else throws NoSuchElementException if there is no next element present.<\/p>\n<p><span style=\"color: #008000;\"><strong>3. void remove( )<\/strong><\/span><\/p>\n<p>This method removes the current element on which iteretor points to or else throws IllegalStateException if remove( ) method is called that is not preceded by a call to next( ) method.<\/p>\n<hr \/>\n<h4><u><\/u><strong>Types of Iterators<\/strong><\/h4>\n<p><span style=\"color: #008000;\"><strong>1. fail-fast Iterator<\/strong><\/span><\/p>\n<p>As name suggests\u00a0fail-fast Iterator\u00a0fails as soon as the\u00a0structure of Collection\u00a0has been changed since traversing has begun. Changes means adding, removing or updating\u00a0any element from collection while one thread is Iterating over that collection.<\/p>\n<p>fail-fast behavior is implemented by keeping\u00a0a modification count and if iteration thread realizes the change in modification count it throws\u00a0ConcurrentModificationException.<\/p>\n<p><span style=\"color: #008000;\"><strong>2. fail-safe Iterator<\/strong><\/span><\/p>\n<p>Contrary to fail-fast Iterator,\u00a0fail-safe iterator\u00a0doesn&#8217;t throw any Exception if Collection is modified structurally while one thread is traversing over\u00a0it as they work on copy of Collection\u00a0instead of original collection and that is why, they are called as fail-safe iterator.<\/p>\n<hr \/>\n<h4><u><\/u><strong>How to Iterate Over Elements<\/strong><\/h4>\n<p>Every collection class has an\u00a0<strong>iterator() method<\/strong>\u00a0which returns an iterator object to the beginning of the collection elements. By using this object, we can access each element in the collection and each element at a time.<\/p>\n<p>To use an Iterator to traverse the collection follow these steps:<\/p>\n<p>1.\u00a0Obtain an Iterator by calling the collection&#8217;s\u00a0iterator( )\u00a0method.<br \/>\n2.\u00a0Create a loop that makes a call to hasNext( ) method.<br \/>\n3. Iterate the loop as long as hasNext()\u00a0method returns true.<br \/>\n4.\u00a0In the loop get each element by calling next( ) method.<\/p>\n<hr \/>\n<p><span style=\"color: #008000;\"><strong>Example of How to use Iterator with List Interface in Java<\/strong><strong>:<\/strong><\/span><\/p>\n<p>Let us discuss Iterator with List Interface with the help of program, following program has been divided into 3 Steps that we will discuss one by one:<\/p>\n<pre>import java.util.*;\r\npublic class IteratorExampleDemo{\r\n\u00a0\r\n\r\npublic static void main(String[] args) {\r\n\r\n\/\/Step 1: create an ArrayList\r\n\r\nList&lt;String&gt; arrayList = new ArrayList&lt;String&gt;();\r\n\r\n\/\/Step 2: Add elements in Array List\r\n\r\narrayList.add(\"I\");\r\narrayList.add(\"Love\");\r\narrayList.add(\"JAVA\");\r\n\u00a0\r\nSystem.out.println(\"Iterate Using Iterator\");\r\n\r\n\/\/Step 3: Iterator object of String type is created\r\nIterator&lt;String&gt; iterator = arrayList.iterator();\r\n\r\n\/\/Step 4: Iterate Using while loop\r\nwhile (iterator.hasNext()) {\r\nSystem.out.println(iterator.next());\r\n}\r\n}\r\n}\r\n<\/pre>\n<p><strong><span style=\"color: #008000;\">\u00a0Output:<\/span><\/strong><\/p>\n<pre>Iterate Using Iterator\r\nI\r\nLove\r\nJAVA\u00a0\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>\u00a0<\/strong><strong>Description:<\/strong><\/span><\/p>\n<ul>\n<li>In Step 1, we have created an object of List Interface that is of String type.<\/li>\n<li>In Step 2, we have used add method to add values in the data structure that we have created in step 1.<\/li>\n<li>In Step 3, we have created an object of Iterator of type String.<\/li>\n<li>In Step 4 we have traversed the data structure with while loop using two methods hasNext() that tell whether there is next element present or not, and next() method that gives the next element during traversing.<\/li>\n<\/ul>\n<p><span style=\"color: #008000;\"><strong>Example of How to use Iterator with Set Interface in Java<\/strong><strong>:<\/strong><\/span><\/p>\n<p>Let us discuss Iterator with Set Interface with the help of program, following program has been divided into 4 Steps that we will discuss one by one.<strong>\u00a0<\/strong><\/p>\n<pre>import java.util.*;\r\n\r\npublic class IteratorExampleDemo{\r\n\r\npublic static void main(String[] args) {\r\n\r\n\/\/Step 1: create an hashSet\r\n\r\nSet&lt;String&gt; hashSet = new HashSet&lt;String&gt;();\r\n\r\n\/\/Step 2: Add elements in hash Set\r\n\r\nhashSet.add(\"I\");\r\nhashSet.add(\"Love\");\r\nhashSet.add(\"JAVA\");\r\n\r\nSystem.out.println(\"Iterate Using Iterator\");\r\n\r\n\/\/ Step 3: Iterator object of String type is created\r\nIterator&lt;String&gt; iterator = hashSet.iterator();\r\n\r\n\/\/Step 4: Iterate Using while loop\r\nwhile (iterator.hasNext()) {\r\nSystem.out.println(iterator.next());\r\n}\r\n}\r\n}\r\n<\/pre>\n<p><strong><span style=\"color: #008000;\">Output:<\/span><\/strong><\/p>\n<pre>Iterate Using Iterator\r\nJAVA\r\nLove\r\nI\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Description:<\/strong><\/span><\/p>\n<ul>\n<li>In Step 1, we have created an object of Set Interface that is of String type.<\/li>\n<li>In Step 2, we have used add method to add values in the data structure that we have created in step 1.<\/li>\n<li>In Step 3, we have created an object of Iterator of type String.<\/li>\n<li>In Step 4 we have traversed the data structure with while loop using two methods hasNext() that tell whether there is next element present or not, and next() method that gives the next element during traversing.<\/li>\n<\/ul>\n<p><span style=\"color: #008000;\"><strong>Example of How to use Iterator with Map Interface in Java<\/strong><strong>:<\/strong><\/span><\/p>\n<p>Iterating over any of the Map implementations like Hashmap, TreeMap etc is not very straight forward as compared to other collections. Let us discuss Iterator with Map Interface with the help of program, following program has been divided into 4 Steps that we will discuss one by one<\/p>\n<pre>import java.util.HashMap;\r\nimport java.util.Iterator;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\n\r\npublic class IteratorMapExample {\r\npublic static void main(String[] args) {\r\n\r\n\/\/Step 1: Object of HahsMap class is Created\r\nMap hashMapObj = new HashMap&lt;String, String&gt;();\r\n\r\n\/\/Step 2: values are added using put() method\r\nhashMapObj.put(\"Abhishek\", \"A+\");\r\nhashMapObj.put(\"Gaurav\", \"B+\");\r\nhashMapObj.put(\"Pryanka\", \"A-\");\r\nhashMapObj.put(\"Rahul\", \"B+\");\r\n\r\nSystem.out.println(\"Using Iterator\");\r\n\r\n\/\/Step 3: object of Iterator is Created\r\nIterator&lt;Map.Entry&lt;String, String&gt;&gt; iterator = hashMapObj.entrySet().iterator() ;\r\n\r\n\/\/Step 4: Traveresed Using While loop\r\nwhile(iterator.hasNext()){\r\nMap.Entry&lt;String, String&gt; bloodGroup = iterator.next();\r\nSystem.out.println(bloodGroup.getKey() +\" :: \"+ bloodGroup.getValue());\r\n}\r\n}\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Output:<\/strong><\/span><\/p>\n<pre>Using Iterator\r\n\r\nRahul :: B+\r\nAbhishek :: A+\r\nGaurav :: B+\r\nPryanka :: A-\r\n<\/pre>\n<p><u><\/u><span style=\"color: #008000;\"><strong>Description:<\/strong><\/span><\/p>\n<ul>\n<li>In Step 1, we have created an object of HashMap class, as we know HashMap has key value pair, so we have defined Key of Integer type, and Value of String type.<\/li>\n<li>In Step 2, we have used put method to add key value pair in the data structure that we have created in step 1.<\/li>\n<li>In Step 3, we have created object of Iterator class, that will be used to further traverse the map.<\/li>\n<li>In Step 4 weh have used while loop, that has used hasNext() method that tell whether there is next element present or not, and next() method that gives the next element during traversing. And we have used two more methods , First is\u00a0 getKey() , which as name suggest retrieves the key and secondly getValue() method that retrieves the values corresponding to the keys.<\/li>\n<\/ul>\n<hr \/>\n<h4><strong>Why use Iterator when we have Enumerator<\/strong><\/h4>\n<p>Both\u00a0Iterator\u00a0and\u00a0Enumerator\u00a0is used for traversing the collection, then why we need Iterator? Following points will tell why we need Iterator:<\/p>\n<ul>\n<li>Iterator\u00a0is more enhanced as extra method\u00a0 remove ()\u00a0is provided by which we can modify the collection which is not available in Enumeration .<\/li>\n<li>Iterator\u00a0 is more secure as it doesn\u2019t allow another thread to modify the collection when some another thread is traversing the collection and throwsconcurrentModificationException.<\/li>\n<li>Along with above benefits names of methods defined in Iterator are also very convenient\u00a0which is not major difference but make use of iterator more easy.<\/li>\n<\/ul>\n<hr \/>\n<h4><strong>Iterator\u00a0Important Points<\/strong><\/h4>\n<ul>\n<li>Iterators are of two types Fail-Fast and Fail-safe, Use Fail-fast when no modifications are needed, else use Fail-safe When modifications such as remove are needed<\/li>\n<li>Iterator supports Generics, so always use generic type instead using it as Raw Type<\/li>\n<li>Iterator has remove() method which is used instead of using for each loop to avoid ConcurrentModificationException<\/li>\n<li>List collection type also supports ListIteratorwhich has\u00a0add()\u00a0method to add elements in collection while Iterating that we will discuss in our next topic<\/li>\n<\/ul>\n<hr \/>\n<h4><strong>Iterator Quick Revision Points<\/strong><\/h4>\n<ul>\n<li>Iterator is an Enhancement over Enumeration as it has remove() method<\/li>\n<li>Iterator is ThreadSafe as compared to Enumeration<\/li>\n<li>Use fail-fast when no modification is needed, use fail-safe when we have to modify data structure while traversing<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>There are different ways by which we can traverse over elements that are for-loop, while loop, do-while, for each loop\u00a0etc. They all are index based on traversing methods. But as we know Java is purely\u00a0object oriented\u00a0 programming language in which we always have possible ways of doing things using objects. So\u00a0Iterator\u00a0is a way to traverse &hellip; <a href=\"https:\/\/abhiandroid.com\/java\/iterator\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Iterator In Java With Example<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"home.php","meta":{"footnotes":""},"class_list":["post-1194","page","type-page","status-publish","hentry"],"psp_head":"<title>Iterator In Java With Example \u2013 Abhi Android<\/title>\r\n<meta name=\"description\" content=\"Java Iterator is an Interface that allows us to traverse the collection objects and access the elements of that collection. Basically List Interface and set Interface provides the iterator.\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/java\/iterator\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/pages\/1194","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/comments?post=1194"}],"version-history":[{"count":0,"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/pages\/1194\/revisions"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/java\/wp-json\/wp\/v2\/media?parent=1194"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}