Why you are getting ConcurrentModificationException
?
That's because you are trying to modify the collection while iterating over it's items. The only safe way to modify your collection during iteration Iterator.remove()
; The same applies for Iterator.add()
(Whether you delete or add an item it counts as a modification).
JDK < 8 SOLUTION
List<String> sourceList = new ArrayList();
List<String> destList = new ArrayList();
sourceList.add("A1");
sourceList.add("A2");
sourceList.add("A3");
sourceList.add("A1B1");
sourceList.add("C1");
Iterator<String> iterator = sourceList.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if(s.startsWith("A"){
destList.add(s);
iterator.remove(s);
}
}
JDK > 8 SOLUTION
List<String> destList = sourceList.stream()
.filter(item -> item.startsWith("A"))
.collect(Collectors.toList());
Note that Java streams
use Spliterator
which quite different than an Iterator
.
A stream source is described by an abstraction called Spliterator. As its name suggests, Spliterator combines two behaviors: accessing the elements of the source (iterating), and possibly decomposing the input source for parallel execution (splitting).
For further details , i advise you to check this interesting post about how streams works under the hood