Tutorials With Examples

Tutorials for beginners and Professionals

Java ArrayList Iterator Example

In this example we will see how to iterate through ArrayList elements. ArrayList provides the the handle in the form of iterator to traverse through all the elements.

Iterator provides the following two important method to loop through the element.

  • boolean hasNext() :Returns true if the iteration has more elements.
  • E next(): Returns the next element in the iteration.
  • void remove() :   Removes from the underlying collection the last element returned by the iterator.

Example Code of Java ArrayList Iterator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.tutorialswithexamples.arraylist;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class ArrayListIteratorExample {
    public ArrayListIteratorExample() {
        super();
    }
 
    public static void main(String[] args) {
        //Create an ArrayList Object
        List<String> users = new ArrayList<String>();
 
        users.add("Alfred");
        users.add("Paul");
        users.add("James");
        users.add("Thomas");
        users.add("Bert");
        users.add("Rani");
        users.add("Anita");
 
        System.out.println("Size of the ArrayList : " + users.size());
        //Iterating over ArrayList
        Iterator<String> userIterator = users.iterator();
 
        while (userIterator.hasNext()) {
            String username = userIterator.next();
            System.out.println(username);
 
            //Remove "James" from the list
            if ("James".equals(username)) {
                userIterator.remove();
            }
        }
        System.out.println("Size of the ArrayList After Removing James : " +
                           users.size());
    }
}

ArrayList Iterator Example Output

1
2
3
4
5
6
7
8
9
Size of the ArrayList : 7
Alfred
Paul
James
Thomas
Bert
Rani
Anita
Size of the ArrayList After Removing James : 6

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

, ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

No Comments
EmailEmail
PrintPrint
WP Socializer Aakash Web