我想从给定字符串中删除ArrayList
中出现的所有单词。
我的相框上有三个按钮。一个添加单词,第二个删除单词,第三个显示单词。
我有一个名为textvalue
的文本框和名为mylist
的数组列表
我用过:
textValue = text.getText().toLowerCase().trim();
if (mylist.contains(textValue)) {
mylist.removeAll(Arrays.asList(textValue));
label.setText("All occurrences of " + textValue + "removed");
} else {
label.setText("Word not found.");
}
如果我举个例子:mark和mark,它仍然只会删除标记。
我也试过:
textValue = text.getText().toLowerCase().trim();
for (String current : mylist) {
if (current.equalsIgnoreCase(textValue)) {
mylist.removeAll(Collections.singleton(textValue));
label.setText("All occurrences of " + textValue + " removed");
} else {
label.setText("Word not found.");
}
}
只需使用removeIf
mylist.removeIf(value->value.equalsIgnoreCase(textValue));
removeIf
接受Predicate作为参数,因此您定义了相应的lambda表达式,通过忽略区分大小写的来删除所有与textValue
匹配的值
@Deadpool使用removeIf()
的解决方案是最简单的,但我想我也建议使用流解决方案。这有点冗长,但它的优点是,由于您正在创建一个新的List
,即使原始的List
是不可变的,它也可以工作。
mylist = mylist.stream().filter(s -> !s.equalsIgnoreCase(textValue)).collect(Collectors.toList());
基本上,您在这里所做的是流式传输原始List
,返回与Predicate
匹配的每个元素,然后将它们收集到一个新的List
中。
您会注意到,您需要否定equals检查,以便只返回与textValue
不匹配的元素。