Saturday, January 11, 2025
HomeProgrammingWays to iterate over a list in Java

Ways to iterate over a list in Java

In Java, there are several ways to iterate over a list:

  1. For Loop: Use a traditional for loop with an index.
    java
    for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
    }
  2. Enhanced For Loop: A cleaner syntax for iterating over elements.
    java
    for (String item : list) {
    System.out.println(item);
    }
  3. Iterator: Use an Iterator to traverse the list.
    java
    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
    System.out.println(iterator.next());
    }
  4. Stream API: Use the forEach method in streams.
    java
    list.forEach(System.out::println);

These methods provide flexibility for iterating over lists in Java.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x