Java 通过忽略区分大小写从列表中删除单词
我想从给定字符串中删除Java 通过忽略区分大小写从列表中删除单词,java,arraylist,Java,Arraylist,我想从给定字符串中删除ArrayList中出现的所有单词 我的相框上有3个按钮。一个用于添加单词,第二个用于删除单词,第三个用于显示单词 我有一个名为textvalue的文本框和名为mylist 我用过: textValue = text.getText().toLowerCase().trim(); if (mylist.contains(textValue)) { mylist.removeAll(Arrays.asList(textValue));
ArrayList
中出现的所有单词
我的相框上有3个按钮。一个用于添加单词,第二个用于删除单词,第三个用于显示单词
我有一个名为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,它仍然只会删除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
接受作为参数,因此通过忽略区分大小写的@Deadpool使用removeIf()
的解决方案是最简单的,但我想我也建议使用流解决方案,来定义与textValue
匹配的所有值。这有点冗长,但其优点是,由于您正在创建一个新的列表
,即使原始的列表
是不可变的,这也会起作用
mylist = mylist.stream().filter(s -> !s.equalsIgnoreCase(textValue)).collect(Collectors.toList());
基本上,您在这里所做的是将原始的列表
,返回与谓词
匹配的每个元素,然后将它们收集到一个新的列表
您会注意到,您需要否定equals检查,以便只返回那些与
textValue
@Javazzs查找lambda表达式部分value->value.equalsIgnoreCase(textValue)
从列表中获取每个元素(此处命名为value
)如果value.equalsIgnoreCase(textValue)
为true
,则将其删除。适用于Java8及更高版本。
mylist = mylist.stream().filter(s -> !s.equalsIgnoreCase(textValue)).collect(Collectors.toList());