I have a String hashset (called "names") and I want to remove from it all the Strings that contains at least one char that isn't a capital letter. I wrote this code and it doesn't work:
Iterator<String> iterator=names.iterator();
while(iterator.hasNext()) {
for (int i=0; i<iterator.next().length(); i++) {
if (iterator.next().charAt(i) < 'A' || iterator.next().charAt(i) > 'Z') {
names.remove(iterator.next());
}
}
}
Another solution if you are using Java-8 by using removeIf and regex [A-Z]+ like so :
Set<String> names = //.. some inputs
names.removeIf(str -> !str.matches("[A-Z]+")); // remove if not matches [A-Z]+
Note in this solution you don't need to convert your list to an iterator at all, and not need to check your characters by a loop, just you can match by regex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With