Iterating Collections
Use for each, forEach with a lambda, or Iterator when removing while looping.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> l = new ArrayList<>(List.of(1, 2, 3, 4));
l.removeIf(n -> n % 2 == 0);
l.forEach(n -> System.out.print(n + " "));
System.out.println();
}
}Result
1 3
Exercise
Remove by condition.
l.(n -> n > 1)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.