Using a method reference to remove items from a list

What is wrong with my code?

I want to remove all items 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 does not remove anything from the list.

+5
source share
2 answers

"A"::startsWith is a reference to a method that can be assigned to Predicate<String> , and when this Predicate<String> tested on some other String , it checks if the string St24 "A" begins with this other String >, and not vice versa.

list.removeIf(TTT) will not delete anything from list , since "A" does not start with either "Mage" or "Helper".


Instead, you can use the lambda expression:

 Predicate<String> TTT = s -> s.startsWith("A"); 

The only way your source predicate "A"::startsWith removed anything from the list is with the list containing String "A" or an empty String .

+7
source
 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")); 

A method reference combines two methods. **startsWith()** is an instance method. This means that the first parameter in lambda is used as an instance to call the method . The second parameter is passed to the startWith () method itself . This is an example of how method references retain a good bit of input.

0
source

Source: https://habr.com/ru/post/1269976/


All Articles