Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, March 31, 2020

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

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

No comments:

Post a Comment

Please do not add any spam links in the comments section.