2

i have these five way to iterate through ArrayList and these are

public static void main(String[] argv) {

    // create list
    List<String> aList = new ArrayList<String>();

    // add 4 different values to list
    aList.add("eBay");
    aList.add("Paypal");
    aList.add("Google");
    aList.add("Yahoo");

    // iterate via "for loop"
    System.out.println("==> For Loop Example.");
    for (int i = 0; i < aList.size(); i++) {
        System.out.println(aList.get(i));
    }

    // iterate via "New way to loop"
    System.out.println("\n==> Advance For Loop Example..");
    for (String temp : aList) {
        System.out.println(temp);
    }

    // iterate via "iterator loop"
    System.out.println("\n==> Iterator Example...");
    Iterator<String> aIterator = aList.iterator();
    while (aIterator.hasNext()) {
        System.out.println(aIterator.next());
    }

    // iterate via "while loop"
    System.out.println("\n==> While Loop Example....");
    int i = 0;
    while (i < aList.size()) {
        System.out.println(aList.get(i));
        i++;
    }

    // collection stream() util: Returns a sequential Stream with this collection as its source
    System.out.println("\n==> collection stream() util....");
    aList.forEach((temp) -> {
        System.out.println(temp);
    });
}

My question is iterating thru any of these way is same or there is any difference? if they, then which is the best way of doing this, my requirement is removing a element from an arraylist based on some condition.

pks
  • 169
  • 1
  • 9

2 Answers2

2

my requirement is removing a element from an arraylist based on some condition

If you have to remove an element from the ArrayList while iterating over it, using an explicit iterator is the base way (your 3rd option). Use aIterator.remove() to remove the current element.

The enhanced for loop and forEach don't allow you to remove elements, since you don't have an index of the current element, and even if you did, removing an element inside the enhanced for loop will throw ConcurrentModificationException.

The regular for loop and the while loop also allow you to remove elements, since you have the index of the current element, but you should remember to decrement the index after removing an element, since removing an element from an ArrayList shifts all the elements that come after that element to the left.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • For your regular for loop, I find it easy to start at the last element, and iterate to the first element. That way you don't need additional logic with the index. – Clark Kent Jan 28 '16 at 12:52
0

Also, you can use this extension of ArrayList CopyOnWriteArrayList

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html

Its threadsafe and you can do .remove without any problem, at cost of performance comparing with normal ArrayList.

kunpapa
  • 367
  • 1
  • 9