osh*_*hai 3 java lambda java-8
我有一种方法来验证数字中没有负数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);
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以使用方法参考而不是x->x.startsWith("-")?我想过String::startsWith("-")但是没有用.
不,您不能使用方法引用,因为您需要提供参数,并且因为该startsWith方法不接受您尝试谓词的值.您可以编写自己的方法,如下所示:
private static boolean startsWithDash(String text) {
return text.startsWith("-");
}
Run Code Online (Sandbox Code Playgroud)
...然后使用:
.filter(MyType::startsWithDash)
Run Code Online (Sandbox Code Playgroud)
或者作为非静态方法,您可以:
public class StartsWithPredicate {
private final String prefix;
public StartsWithPredicate(String prefix) {
this.prefix = prefix;
}
public boolean matches(String text) {
return text.startsWith(text);
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用:
// Possibly as a static final field...
StartsWithPredicate predicate = new StartsWithPredicate("-");
// Then...
List<String> negatives = numbers.stream().filter(predicate::matches)...
Run Code Online (Sandbox Code Playgroud)
但是你不妨制作StartsWithPredicate工具Predicate<String>,只需传递谓词本身:)
| 归档时间: |
|
| 查看次数: |
408 次 |
| 最近记录: |