Using method reference to remove elements from a List

Hasnain Ali Bohra :

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.

Eran :

"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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466369&siteId=1