7

I use java8 streams. Here is the data structure I have:

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

Then I iterate via the map and list:

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

But get concurrent modification exception:

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 iterating via the map \ list should not cause this kind of behavior.

6
  • 2
    What is lis and how is it related to the mmessage Map? Commented Aug 1, 2016 at 9:21
  • 7
    You can not add valies to the list you are iterating over Commented Aug 1, 2016 at 9:21
  • 1
    @Jens OP is not adding values to the same list (at least we don't know that yet, since we don't know what is lis). Commented Aug 1, 2016 at 9:23
  • yes, i understand this, lis it is just another structure, like lis = new ArrayList< String>(); but you right it fails on it on different reason. Thanks! Commented Aug 1, 2016 at 9:25
  • 1
    lis is a value in the map; this is why it fails. Commented Aug 1, 2016 at 9:28

1 Answer 1

17

I would write this using a full functional style and you shouldn't run into the problem of modifying a list while iterating it.

List<String> strs = mmessage.values().stream()
                            .flatMap(List::stream)
                            .distinct()
                            .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.