我有一个字符串哈希集(称为“名称”),我想从中删除所有至少包含一个非大写字母的字符的字符串。 我写了这段代码,但它不起作用:
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());
}
}
}
最佳答案
如果您使用 Java-8,另一个解决方案是使用 removeIf
和正则表达式 [A-Z]+
像这样:
Set<String> names = //.. some inputs
names.removeIf(str -> !str.matches("[A-Z]+")); // remove if not matches [A-Z]+
请注意,在此解决方案中,您根本不需要将列表转换为迭代器,也不需要通过循环检查字符,只需通过正则表达式进行匹配即可。
关于java - HashSet 迭代器检查字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59015919/