Iterator
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
An iterator is an object that goes through a collection one element at a time:
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.isEmpty())
it.remove(); // remove the CURRENT element — safe
}
for (String s : list) is an iterator too, just hidden. But removing inside a for-each with
list.remove(s) is not allowed: the next step throws a ConcurrentModificationException — the iterator notices
that the collection was changed behind its back.
The short form of the same thing is list.removeIf(s -> s.isEmpty()) (lambdas are in the last module).
Task. The first number is k, followed by words. Using an Iterator, remove from the list all the words shorter than k
characters and all the repeats of the word that has just appeared (a a b → a b). Print the remaining words and
how many were removed.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.