I was reading some info about iterators, enumeration, etc. So I tested some code to check everything out.
First one example:
List<String> list = new ArrayList<>();
list.add("5");
list.add("1");
list.add("2");
list.add("3");
Iterator<String> iterator = list.iterator();
list.remove("1");
iterator.forEachRemaining(System.out::println);
This code makes the correct and expected output:
Exception in thread "main" java.util.ConcurrentModificationException
But when I tested the same code with only 1 change list.iterator() -> list.stream().iterator()
List<String> list = new ArrayList<>();
list.add("5");
list.add("1");
list.add("2");
list.add("3");
Iterator<String> iterator = list.stream().iterator();
list.remove("1");
iterator.forEachRemaining(System.out::println);
The result was:
5
2
3
My main aim is to understand:
- Why is this happens?
- What magic makes only one
stream()method? - What are the advantages and disadvantages of using
stream().iterator?