通过忽略大小写从列表中删除一个单词

Jav*_*zzs 3 java arraylist

我想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.");
                        }
Run Code Online (Sandbox Code Playgroud)

如果我举个例子: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.");
                                }

                            }
Run Code Online (Sandbox Code Playgroud)

Dea*_*ool 8

只需使用removeIf

mylist.removeIf(value->value.equalsIgnoreCase(textValue));
Run Code Online (Sandbox Code Playgroud)

removeIf接受Predicate作为参数,因此您要定义相应的lambda表达式,以textValue通过忽略大小写区分来删除所有与之匹配的值

  • value-> value.equalsIgnoreCase(textValue)部分从列表中获取每个元素(此处命名为value),如果value.equalsIgnoreCase(textValue)为true则将其删除。**适用于Java 8及更高版本。** (2认同)