R AND B
R AND B

Reputation: 51

Remove a word from the List by ignoring case sensitive

I want to delete all occurrences of a word in the ArrayList from a given string .

I have 3 buttons on my frame. One that adds words, a second that removes words, and the third that shows words.

I have a textbox with name textvalue and array list with name mylist

I used:

 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.");
                        }

If I put for example : mark and MARK , it will still only delete mark.

I have also tried:

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.");
                                }

                            }

Upvotes: 3

Views: 2469

Answers (2)

azurefrog
azurefrog

Reputation: 10945

@Deadpool's solution using removeIf() is simplest, but I thought I'd also suggest a stream solution. This is a little more verbose, but has the advantage that, since you're creating a new List, this will work even if the original List is immutable.

mylist = mylist.stream().filter(s -> !s.equalsIgnoreCase(textValue)).collect(Collectors.toList());

Basically what you're doing here is streaming the original List, returning each element that matches the Predicate, and then collecting them into a new List.

You'll notice that you need to negate the equals check, in order to return only those elements that don't match textValue.

Upvotes: 1

Ryuzaki L
Ryuzaki L

Reputation: 40078

Just use removeIf

mylist.removeIf(value->value.equalsIgnoreCase(textValue));

removeIf accepts Predicate as an argument, So you are defining corresponding lambda expression to delete all values that matches to textValue by ignoring case sensitive

Upvotes: 11

Related Questions