What's wrong with my code?
I want to remove all the elements starting with A from the List
list
:
public static void main(String[] args) {
Predicate<String> TTT = "A"::startsWith;
List<String> list = new ArrayList<>();
list.add("Magician");
list.add("Assistant");
System.out.println(list); // [Magician, Assistant]
list.removeIf(TTT);
System.out.println(list); // expected output: [Magician]
}
However, removeIf
doesn't remove anything from the list.
There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.
"A"::startsWith
is a method reference that can be assigned to a Predicate<String>
, and when that Predicate<String>
is tested against some other String
, it would check whether the String "A"
starts with that other String
, not the other way around.
list.removeIf(TTT)
won't remove anything from list
, since "A" doesn't start with neither "Magician" nor "Assistant".
You can use a lambda expression instead:
Predicate<String> TTT = s -> s.startsWith("A");
The only way your original "A"::startsWith
predicate would remove anything from the list is if the list would contain the String
"A"
or an empty String
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With