Iterator.remove()
To update a collection while iterating we can use Iterator.remove()
List<String> list = new ArrayList<>();
Iterator<Integer> iter = list.iterator();
while (iter.hasNext()) {
if (iter.next() == 5) {
iter.remove(); // <<---
}
}
This also uses iterator but the syntax is quite eassier
var list = new ArrayList<>(List.of("a", "b", "c", "a1"));
list.removeIf(x -> x.startsWith("a")); // <<---
System.out.println(list); // Output -> [b, c]
Java 8 Streams
I would still prefer using immutable collections and use the stream functions instead of updating the collection in place..
var list = List.of("a", "b", "c", "a1");
var updatedList = list.stream()
.dropWhile(x -> x.startsWith("a"))
.collect(Collectors.toList());
System.out.println(updatedList); // Output -> [b, c]