0

as the title suggests, I need to fix this exception: java.util.ConcurrentModificationException: null. Below the code that goes into error:

Map<String, List<Note>> noteByCod = notes.stream().collect(Collectors.groupingBy(Note::getCod));
noteByCod.forEach((k, v) -> v.forEach(note -> {
       if (!note.getVer() || !StringUtils.isEmpty(note.getError())) {
                noteByCod.remove(k);
       }
}));

the problem is that it is not possible to modify the collection you are iterating on, in this case how would you solve?

1
  • 3
    Even simpler noteByCod.values().removeIf(v -> v.stream().anyMatch(note -> !note.getVer() || !StringUtils.isEmpty(note.getError()))); And when you clean up your API and make a definite decision whether an error free note should return null or an empty string from getError(), you can get rid of StringUtils.isEmpty and use either getError() != null or !getError().isEmpty(). Commented Apr 14, 2021 at 11:01

2 Answers 2

3

You can rewrite this to use an old-fashioned Iterator over the entry set. Iterator has a remove method that allows the last-returned object to be removed:

Map<String, List<Note>> noteByCod = ...;
Iterator<Map.Entry<String, List<Note>> it = noteByCode.entrySet().iterator();
while (it.hasNext()) {
  if (it.next().getValue().stream().anyMatch(
        note -> !note.getVer() || !StringUtils.isEmpty(note.getError()))) {
    it.remove();
  }
}));
Sign up to request clarification or add additional context in comments.

2 Comments

The Stream way would require to collect a list of notes to remove, so this is definitely a more direct, efficient solution. If not the noteByCode is redone.
@EngineerTop: removeIf is actually a nicer solution, well done. If you find a solution, you can and should post it as an answer, please don't edit your question to include it.
3

Thanks, I finally solved it like this:

Map<String, List<Note>> noteByCod = notes.stream().collect(Collectors.groupingBy(Note::getCod));
noteByCod.values().removeIf(v -> v.stream().anyMatch(note -> !note.getVer() || !StringUtils.isEmpty(note.getError())));

1 Comment

Good job ! indeed

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.