Removing a String from an ArrayList

So I have a problem that takes the names of people from a user and stores them in an ArrayList(personalNames). After that I need to take that list and remove any name that has anything besides letters a-z (anything with numbers or symbols) in it and put them into a separate ArrayList(errorProneNames) that holds the errors. Could someone help me with the removal part?

public class NameList {

public static void main(String[] args) {

    ArrayList<String> personalNames = new ArrayList<String>();
    Scanner input = new Scanner(System.in);
    String answer;

    do{
    System.out.println("Enter the personal Names: ");
    String names = input.next();

    personalNames.add(names);
    System.out.println("would you like to enter another name (yes/no)?");
    answer = input.next();
     } while (answer.equalsIgnoreCase("yes"));



    ArrayList<String> errorProneNames = new ArrayList<String>();


}

}

Jon Skeet
people
quotationmark

If it's the "how do I remove an element from an ArrayList<>" part which is causing problems, and you want to check all the values, you probably want to use an Iterator and call remove on that:

for (Iterator<String> iterator = personalNames.iterator(); iterator.hasNext(); ) {
    String name = iterator.next();
    if (isErrorProne(name)) {
        iterator.remove();
    }
}

Note that you mustn't remove an element from a collection while you're iterating over it in an enhanced-for loop except with the iterator. So this would be wrong:

// BAD CODE: DO NOT USE
for (String name : personalNames) {
    if (isErrorProne(name)) {
        personalNames.remove(name);
    }
}

That will throw a ConcurrentModificationException.

Another option would be to create a new list of good names:

List<String> goodNames = new ArrayList<>();
for (String name : personalNames) {
    if (!isErrorProne(name)) {
        goodNames.add(name);
    }
}

Now, if your real problem is that you don't know how to write the isErrorProne method, that's a different matter. I suspect that you want to use a regular expression to check that the name only contains letters, spaces, hyphens, and perhaps apostrophes - but you should think carefully about exactly what you want here. So you might want:

private static boolean isErrorProne(String name) {
    return !name.matches("^[a-zA-Z \\-']+$");
}

Note that that won't cope with accented characters, for example. Maybe that's okay for your situation - maybe it's not. You need to consider exactly what you want to allow, and adjust the regular expression accordingly.

You may also want to consider expressing it in terms of whether something is a good name rather than whether it's a bad name - particularly if you use the last approach of building up a new list of good names.

people

See more on this question at Stackoverflow