Java8 java.util.ConcurrentModificationException during cycle forEach

I use streams java8. Here is a data structure that I have:

Map< String, List< String >> mmessage = getSomeMessage(); 

Then I climb over the map and list:

  mmessage.entrySet().stream().forEach( entry -> { entry.getValue().stream().forEach( li -> { if ( lis.indexOf( li ) == - 1 ) { lis.add( lineItem ); } }); }); (entry -.> {  mmessage.entrySet().stream().forEach( entry -> { entry.getValue().stream().forEach( li -> { if ( lis.indexOf( li ) == - 1 ) { lis.add( lineItem ); } }); }); 

But get an exception for simultaneous modification:

 java.util.ConcurrentModificationException at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1380) at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580) at com.web3.buyer.roomba.RoombaTurn.lambda$received$3(RoombaTurn.java:296) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580) at com.web3.buyer.roomba.RoombaTurn.received(RoombaTurn.java:295) at com.web3.buyer.SystemBus.lambda$publishToTheQueue$0(SystemBus.java:51) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) 

From my understanding, that the iteration through the map \ list should not cause this kind of behavior.

+5
source share
1 answer

I would have written it, using the full functional style, and you do not have to face the problem of changing the list in its repetition.

 List<String> strs = mmessage.values().stream() .flatMap(List::stream) .distinct() .collect(Collectors.toList()); 
+14
source

All Articles