top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are different ways to iterate over a list in java?

0 votes
558 views
What are different ways to iterate over a list in java?
posted Jan 18, 2018 by Ammy Jack

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

We can iterate over a list in two different ways – using iterator and using for-each loop.

List<String> strList = new ArrayList<>();

//using for-each loop
for(String obj : strList){
    System.out.println(obj);
}

//using iterator
Iterator<String> it = strList.iterator();
while(it.hasNext()){
    String obj = it.next();
    System.out.println(obj);
}

Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException.

answer Jan 19, 2018 by Jon Deck
...