简体   繁体   中英

Using method reference to remove elements from a List

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.

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

BiPredicate<String, String> b1 = String::startsWith;
BiPredicate<String, String> b2 = (string, prefix) -> string.startsWith(prefix);
System.out.println(b1.test("chicken", "chick"));
System.out.println(b2.test("chicken", "chick"));

The method reference combines two techniques. **startsWith()** is an instance method. This means that the first parameter in the lambda is used as the instance on which to call the method . The second parameter is passed to the startsWith() method itself . This is example of how method references save a good bit of typing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM