Ways to iterate over a list in Java
There are several ways to iterate over a List
in Java. Here are some of the most common approaches:
- For loop: You can use a traditional for loop to iterate over the elements of a list. Here's an example:
List<String> list = ...;
for (int i = 0; i < list.size(); i++) {
String element = list.get(i);
// do something with the element
}
- For-each loop: You can use a for-each loop, also known as a "enhanced for loop", to iterate over the elements of a list. This is a more concise and easy-to-read syntax:
List<String> list = ...;
for (String element : list) {
// do something with the element
}
- Iterator: You can use an
Iterator
to iterate over the elements of a list. This allows you to remove elements from the list while iterating, as well as to perform other operations such as skipping elements or stopping the iteration early. Here's an example:
List<String> list = ...;
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
// do something with the element
}
- Stream API: If you are using Java 8 or later, you can use the
Stream
API to iterate over the elements of a list. This is a more functional and declarative style of iteration, and it allows you to perform operations such as filtering, mapping, and reducing the elements of the list. Here's an example:
List<String> list = ...;
list.stream()
.forEach(element -> {
// do something with the element
});
There are many other ways to iterate over a list in Java, depending on your needs and preferences. These are just a few examples to get you started.