Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using method reference to remove elements from a List

Tags:

java

java-8

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.

like image 428
Hasnain Ali Bohra Avatar asked Jul 19 '17 09:07

Hasnain Ali Bohra


People also ask

How do I remove objects from a 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.


1 Answers

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

like image 108
Eran Avatar answered Nov 14 '22 20:11

Eran