$show=/label

How to Use Iterator in Java? Java 8 Iterator Examples on ArrayList, HashSet, HashMap

SHARE:

A quick practical complete guide to Iterator in java. Iterator is used to traverse over the values of List and Set. Example programs on Java 8 Iterator forEachRemaining() method.

1. Introduction


In this article, We will learn the Iterator interface in java and what are its methods. Let us write examples on how to use the Iterator in java.

Iterator is used to iterate or traverse over a Collection such as ArrayList, LinkedList or HashSet. Iterator is a replacement to the Enumeration because Enumeration does not allow to remove the values from underlying collection and methods names are not readable (understandable).

In the previous post, we have discussed in detail on ConcurrentModificationException and how to avoid concurrency.

How to Use Iterator in Java? Java 8 Iterator Examples on ArrayList, HashSet, HashMap




2. Iterator Methods


Iterator interface has a total of 4 methods but initially, it was introduced with 3 methods but java 8 has come up with a new method.

2.1 boolean hasNext()

This method tells us whether the collection has the next element to fetch. If this method returns true that indicates there few elements in the collection. False indicates no values further to process.

boolean hasnextValue = it.hasnext();

2.2 E next()

next() method is used to get the next value from collection. Before calling next() method, it is suggested to call hasNext() method. If hasNext() returns true then only invoke next() method.

String value = it.next();

If you call next() method directly before hasNext() method and if there are no values in the list or set then it will throw runtime exception saying NoSuchElementException.
We will show the example program to simulate this exception.

2.3 default void remove()


remove() is allowed to on iterator instance. If you invoke remove() method then the value will be removed from the original list.

it.remove();

Always remove() method must be called after next() method. If you call directly first remove() method that will throw runtime exception "java.lang.IllegalStateException".
An example is shown at the end of this article.

2.4 default void forEachRemaining(Consumer< super E> action)


This the new method added in java 8 changes which is a default method and Iterate implementation classes are not required to implement. Because this default method will be available to all collection Integrate classes. This method takes the Consumer functional interface. The consumer has a functional method accept(T t) that takes only one parameter and does not return any value whereas BiConcumer takes two values.

it.forEachRemaining( System.out.println(value));

If the null value is provided that will produce NullPointerException.

it.forEachRemaining(null);

3. ArrayList iterator() Example


To create an Iterate instance, we must call the iterator() method on ArrayList. ArrayList can be used in real-time applications.

package com.java.w3schools.blog.arraylist;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

/**
 * 
 * ArrayList Iterate Example
 * 
 * @author JavaProgramTo.com
 *
 */

public class ArrayListIteratorExample {

 public static void main(String[] args) {

  ArrayList<String> list = new ArrayList<String>(Arrays.asList("One", "Two", "Three", "Four"));

  System.out.println("list values : " + list);

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

  while (it.hasNext()) {
   String value = it.next();
   System.out.println(value);
  }

 }

}

Output:

list values : [One, Two, Three, Four]
One
Two
Three
Four

4. HashSet iterator() Example


Let us write an example program to iterate over HashSet.

public class HashsetIteratorExample {

 public static void main(String[] args) {

  Set<Integer> set = new HashSet<Integer>();

  set.add(1);
  set.add(2);
  set.add(3);
  set.add(1);

  Iterator<Integer> it = set.iterator();

  while (it.hasNext()) {
   int value = it.next();
   System.out.println(value);
   it.remove();
  }

 }

}

5. HashMap iterate example



public class HashMapIteratorExample {

 public static void main(String[] args) {

  Map<Integer, String> map = new HashMap<Integer, String>();

  map.put(1, "");
  map.put(2, "");
  map.put(3, "");
  map.put(1, "");

  Iterator<Integer> it = map.keySet().iterator();

  while (it.hasNext()) {
   int value = it.next();
   System.out.println("key : " + value);
  }

 }

}

6. next() NoSuchElementException Example


If next() method is called invoked continuesly without calling hasNext() method that causes to NoSuchElementException.

ArrayList<String> countries = new ArrayList<String>();

countries.add("India");
countries.add("USA");

System.out.println("list values : " + countries);

Iterator<String> it = countries.iterator();

while (true) {
 it.next();
}

Output:

list values : [India, USA]
Exception in thread "main" java.util.NoSuchElementException
 at java.util.ArrayList$Itr.next(ArrayList.java:862)
 at com.java.w3schools.blog.iterate.ArrayListIteratorExample.main(ArrayListIteratorExample.java:29)


7. remove() IllegalStateException Example


If the remove() method is called before the next() method or no next() method is invoked then it will cause to IllegalStateException exception.

Iterator<String> it = countries.iterator();

while (it.hasNext()) {
 it.remove();
 String country = it.next();
}

Output:

Exception in thread "main" java.lang.IllegalStateException
 at java.util.ArrayList$Itr.remove(ArrayList.java:872)
 at com.java.w3schools.blog.iterate.ArrayListIteratorExample.main(ArrayListIteratorExample.java:29)

8. Iterate forEachRemaining() example


This is the most convenient way to iterate over the list or set because it takes care of calling hasNext() and next() methods internally and it gives the value in the order they appear in the collection.

public class IteratorforEachRemainingExample {

 public static void main(String[] args) {

  ArrayList<String> countries = new ArrayList<String>();

  countries.add("Candada");
  countries.add("UK");
  countries.add("India");
  countries.add("USA");


  countries.iterator().forEachRemaining( country -> System.out.println(country));
 }

}

Output:

Candada
UK
India
USA

If null is passed to this method then NullPointerException.

countries.iterator().forEachRemaining(null);

Exception stack trace:

Exception in thread "main" java.lang.NullPointerException
 at java.util.Objects.requireNonNull(Objects.java:203)
 at java.util.ArrayList$Itr.forEachRemaining(ArrayList.java:888)
 at com.java.w3schools.blog.iterate.IteratorforEachRemainingExample.main(IteratorforEachRemainingExample.java:25)


9. Conclusion


In this article, We've seen how to use the Iterator and its methods over Collection API classes. What are the good practices when using Iterator methods?
What are the exceptions thrown at the runtime if we do not use it properly? This is a complete guide to the Iterate interface including java 8 new method.

GitHub for example

Ref 1

Java 8 for each

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: How to Use Iterator in Java? Java 8 Iterator Examples on ArrayList, HashSet, HashMap
How to Use Iterator in Java? Java 8 Iterator Examples on ArrayList, HashSet, HashMap
A quick practical complete guide to Iterator in java. Iterator is used to traverse over the values of List and Set. Example programs on Java 8 Iterator forEachRemaining() method.
https://1.bp.blogspot.com/-2Jw1_ZhlkwQ/XoOHJYNZ-GI/AAAAAAAACaY/nyWKLh_4t30nw2BM4t5r-rJaq_NhNB2sQCLcBGAsYHQ/s640/How%2Bto%2BUse%2BIterator%2Bin%2BJava%253F%2BJava%2B8%2BIterator%2BExamples%2Bon%2BArrayList%252C%2BHashSet%252C%2BHashMap.png
https://1.bp.blogspot.com/-2Jw1_ZhlkwQ/XoOHJYNZ-GI/AAAAAAAACaY/nyWKLh_4t30nw2BM4t5r-rJaq_NhNB2sQCLcBGAsYHQ/s72-c/How%2Bto%2BUse%2BIterator%2Bin%2BJava%253F%2BJava%2B8%2BIterator%2BExamples%2Bon%2BArrayList%252C%2BHashSet%252C%2BHashMap.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/03/how-to-use-iterator-in-java-java-8.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/03/how-to-use-iterator-in-java-java-8.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content