Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet iterator checking letters

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());
        }
    }
}
like image 812
Hilla Barnea Avatar asked Feb 17 '26 07:02

Hilla Barnea


1 Answers

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.

like image 118
YCF_L Avatar answered Feb 19 '26 20:02

YCF_L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!