Java技术问题:移除List<String>中以&开头元素时出现报错
&-Prefixed Elements from List<String> Without Errors Hey there! Let's break down why you're running into errors when trying to remove elements starting with & from your List<String>—and how to fix it fast.
The most common issue here is a ConcurrentModificationException, which pops up when you try to modify the list (like removing an element) while iterating over it with a regular for-each loop. Here are three reliable solutions:
1. Use Iterator (Safe for All Java Versions)
This is the classic, foolproof way to modify a list during iteration. The Iterator interface's remove() method is designed explicitly for this scenario, so it won't trigger concurrent modification errors.
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListCleanup { public static void main(String[] args) { List<String> myList = new ArrayList<>(List.of("&item1", "validItem", "&item2", "anotherValid")); Iterator<String> iterator = myList.iterator(); while (iterator.hasNext()) { String currentItem = iterator.next(); if (currentItem.startsWith("&")) { iterator.remove(); // Safely remove the element without breaking iteration } } System.out.println(myList); // Output: [validItem, anotherValid] } }
2. Use Java 8+ removeIf() (Cleanest Option)
If you're using Java 8 or later, the removeIf() method on Collection is your best bet. It handles the iteration safely under the hood, and the code is super concise.
import java.util.ArrayList; import java.util.List; public class ListCleanup { public static void main(String[] args) { List<String> myList = new ArrayList<>(List.of("&item1", "validItem", "&item2", "anotherValid")); // Directly modify the original list to remove &-prefixed elements myList.removeIf(item -> item.startsWith("&")); System.out.println(myList); // Output: [validItem, anotherValid] } }
You can also use Streams to create a new filtered list if you don't want to modify the original:
List<String> filteredList = myList.stream() .filter(item -> !item.startsWith("&")) .toList(); // Or collect(Collectors.toList()) for older Java versions
3. Avoid Common Mistakes
Steer clear of these error-prone approaches:
❌ Bad: For-each loop with direct removal
// This will throw ConcurrentModificationException for (String item : myList) { if (item.startsWith("&")) { myList.remove(item); } }
❌ Risky: Index-based loop (easy to mess up)
While you can adjust the index manually, it's easy to skip elements or hitIndexOutOfBoundsExceptionif you're not careful:for (int i = 0; i < myList.size(); i++) { if (myList.get(i).startsWith("&")) { myList.remove(i); i--; // Need to decrement index to avoid skipping the next element } }
Final Recommendation
Stick with removeIf() if you're on Java 8+—it's clean, readable, and safe. For older Java versions, use Iterator. Both methods will prevent the errors you're seeing and get the job done reliably.
内容的提问来源于stack exchange,提问作者Ahmed Khairy

