此方法接受一组字符串,然后删除该组的偶数长度的所有字符串。 问题是我知道集合不计入元素所以我必须使用迭代器,但是,如何从集合中删除特定的“元素”?
private static void removeEvenLength(Set<String> thing) {
Iterator<String> stuff = thing.iterator();
while (stuff.hasNext()) {
String temp = stuff.next();
if (temp.length() %2 == 0) {
temp.remove(); // What do I do here?
}
}
}
答案 0 :(得分:5)
尝试使用迭代器
stuff.remove();
答案 1 :(得分:3)
private static void removeEvenLength(Set<String> thing) {
thing.add("hi");
thing.add("hello");
Iterator<String> stuff = thing.iterator();
System.out.println("set"+thing);
while (stuff.hasNext()) {
String temp = stuff.next();
if (temp.length() %2 == 0) {
stuff.remove();
}
}
System.out.println("set"+thing);
}
答案 2 :(得分:0)
如果您使用的是Java 8,可以尝试这样的方法:
public static void removeEvenLength(final Set<String> set){
set.stream().filter(string -> string.length() % 2 == 0).forEach(set::remove);
}
答案 3 :(得分:0)
您不能这样做,因为Set类在尝试不使用迭代器从集合中删除元素时会抛出ConcurrentModificationException快速失败。