Java – references a method with specified parameters (for lambda)
•
Java
I have a way to verify that there are no negative numbers in the number list:
private void validateNoNegatives(List<String> numbers) { List<String> negatives = numbers.stream().filter(x->x.startsWith("-")).collect(Collectors.toList()); if (!negatives.isEmpty()) { throw new RuntimeException("negative values found " + negatives); } }
Can I use method references instead of X - > x.startswith ("–")? I thought about string:: startswith ("–") but it didn't work
Solution
No, you cannot use method references because you need to provide parameters and because the startswith method does not accept the value of the predicate you are trying You can write your own method, as follows:
private static boolean startsWithDash(String text) { return text.startsWith("-"); }
... then use:
.filter(MyType::startsWithDash)
Or as a non static method, you can:
public class StartsWithPredicate { private final String prefix; public StartsWithPredicate(String prefix) { this.prefix = prefix; } public boolean matches(String text) { return text.startsWith(text); } }
Then use:
// Possibly as a static final field... StartsWithPredicate predicate = new StartsWithPredicate("-"); // Then... List<String> negatives = numbers.stream().filter(predicate::matches)...
But you can implement startswithpredicate as predicate < string > and just pass the predicate itself:)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码