我使用java8流。这是我的数据结构:
Map< String, List< String >> mmessage = getSomeMessage();
然后我通过地图和列表进行迭代:
mmessage.entrySet().stream().forEach( entry -> {
entry.getValue().stream().forEach( li -> {
if ( lis.indexOf( li ) == - 1 ) {
lis.add( lineItem );
}
});
});
但是获得并发修改异常:
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)
根据我的理解迭代通过map \ list不应该导致这种行为。
答案 0 :(得分:15)
我会用完整的功能样式来编写它,你不应该在迭代时遇到修改列表的问题。
List<String> strs = mmessage.values().stream()
.flatMap(List::stream)
.distinct()
.collect(Collectors.toList());