Skip to main content

Iterators in java 8


An Iterator is an object that enables you to navigate through a collection and to remove elements from the collection selectively, if desired. You get an Iterator for a collection by calling its iterator method. The following is the Iterator interface.

public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove(); //optional
}

The hasNext() method returns true if the iteration has more elements, and the next() method returns the next element in the iteration.

 The remove() method removes the last element that was returned by next from the underlying Collection. The remove method may be called only once per call to next and throws an exception if this rule is violated.

[NoteIterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.]

Use Iterator instead of the for-each :

  • Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.
  • Iterate over multiple collections in parallel.
The following method shows you how to use an Iterator to filter an arbitrary Collection — that is, traverse the collection removing specific elements.

public static void main(String args[]) {
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
   for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
      if (iter.next().equals("c")) {
                        iter.remove();
                    }
           }
           System.out.println(list);
    }

Output: [a, b, d]

A brief example:

public class Test_Iterator {

    public static void main(String args[]) {
        // Create an array list
        ArrayList al = new ArrayList();

        // add elements to the array list
        al.add("C");
        al.add("A");
        al.add("E");
        al.add("B");
        al.add("D");
        al.add("F");

        // Use iterator to display contents of al
        System.out.print("Original contents of al: ");
        Iterator itr = al.iterator();

        while (itr.hasNext()) {                          //------hasNext()---------
            Object element = itr.next();                //-------next()---------
            System.out.print(element + " ");
        }
}

Output: Original contents of al: C A E B D F



Comments

Popular posts from this blog

A brief history of java

A brief history of java: James Gosling The history of Java Language is more interesting. The history of Java starts from “Green Project”. In 1991 The Green Project initiated by James Gosling , Mike Sheridan , and Patrick Naughton . A small group of Sun engineers called the "Green Team" believed that the next wave in computing was the union of digital consumer devices and computers. Led by James Gosling, the team worked around the clock and created the programming language that would revolutionize our world – Java.   The language was initially called Oak ( Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A., France, Germany, Romania etc ). Later the project went by the name Green and was finally renamed Java , from Java coffee (produced in the Java, is an island of Indonesia).  Sun Microsystem s released the first public implementation as Java 1.0 in 1995. It promised "Write Once, Run Anywhere" (WORA), pr

Features of Java:

Features of Java: In   Java Programming language we introduce with some keyword like Object-oriented, Simple, Portable Platform independent   etc.   Yes! These are feature of Java. There are many features in Java. They are also known as java buzzwords. The main features of Java are: Simple Object-Oriented   Portable   Platform independent     Secured     Robust   Architecture-neutral   Dynamic     Interpreted     High Performance     Multithreaded     Distributed The Java Features are given below in detail. Simple Java is easy to learn and its syntax is quite simple, clean and easy to understand. The confusing and ambiguous concepts of C++ are either left out in Java or they have been re-implemented in a cleaner way. No need to remove unreferenced objects because there is Automatic Garbage Collection in java. E.g.: Pointers and Operator Overloading are not there in java but were an important part of C++.   Object-oriented

What is Java?

What is Java? The first released of Java on Jan 23, 1996 by Sun Microsystems. Java is a computer programming language. It is a widely used programming language. It is the most popular programming language for Android Smartphone. It’s known as a high-level language because it can be read and written easily by humans. Once a program has been written, the high-level instructions are translated into numeric codes that computers can understand and execute. It enables programmers to write computer instructions using English-based commands instead of having to write in numeric codes. Java was designed to have the look and feel of the  C++  language, but it is simpler to use than C++ and enforces an  object-oriented programming  model. Java can be used to create complete applications that may run on a single computer or be distributed among servers and clients in a network. It can also be used to build a small application module or applet for use as part of a webpage.