Iterator Interface | Java

/Iterator Interface | Java

Java Iterator interface used to iterate over the elements in a collection (list, set or map). It helps to retrieve the specified collection elements one by one and perform operations over each element.

Iterator Methods

  • boolean hasNext():Returns true if the iteration has more elements.
  • E next(): Returns the next element in the iteration.
  • default void remove(): It removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next(). If the underlying collection is modified while the iteration is in progress in any way other than by calling remove() method, iterator will throw an ConcurrentModificationException. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behaviour at an undetermined time in the future.
  • default void forEachRemaining(Consumer action): This method performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified.

Example

/* ArrayList Example */
ArrayList<String> list = new ArrayList<>();
         
list.add("A");
list.add("B");
list.add("C");
list.add("D");
 
// Get iterator
Iterator<String> iterator = list.iterator();

// Print all the element of the list 
iterator.forEachRemaining(System.out::println);

// Iterate over all elements
while(iterator.hasNext())
{
    // Get current element
    String value = iterator.next();
     
    // Remove element
    if(value.equals("B")) {
        iterator.remove();
    }
}

/* HashMap Example */
HashMap<Integer, String> map = new HashMap<>();
         
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
map.put(4, "D");
 
// Get iterator for the keys
Iterator<String> iterator = map.keys().iterator();

// Get iterator for values
//Iterator<String> iterator = map.values().iterator();
 
// Iterate over all keys
while(iterator.hasNext())
{
    String key = iterator.next();
}

 

 

August 15th, 2019|Categories: Programming|Tags: |
avatar
  Subscribe  
Notify of