openrewrite / openrewrite/rewrite-static-analysis
replace `Collection` removal using loops with `removeIf` to avoid `ConcurrentModificationException`
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 62
- Forks
- 112
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 40
Description
List<Integer> integers = new ArrayList<>();
integers.add(1);
integers.add(2);
integers.add(3);
integers.add(4);
for (Integer integer : integers) {
if (integer == 2) {
integers.remove(integer);
}
}
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997)
at Scratch.main(scratch_5.java:12)
A common solution to the problem above is to use iterators :
Iterator<Integer> iter = integers.iterator();
while (iter.hasNext()) {
Integer i = iter.next();
if (i == 2){
iter.remove();
}
}
But using removeIf is more compact and cleaner. It also avoid ConcurrentModificationException
integers.removeIf(integer -> integer == 2);
Streams is another option, but doing so will return a new list and that is likely not desirable in this case
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No source file or test is named. Start by locating the Java static-analysis recipe that handles collection-removal loops, then compare its existing behavior with the examples in this issue. Done means the matching loop is replaced with removeIf while preserving in-place removal and avoiding ConcurrentModificationException.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- tooling
- Issue type
- Refactor
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100