引用具有指定参数的方法(用于lambda)

时间:2014-07-22 12:16:55

标签: 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);
    }
}

是否可以使用方法参考而不是x->x.startsWith("-")?我想过String::startsWith("-")但是没有用。

1 个答案:

答案 0 :(得分:7)

不,您不能使用方法引用,因为您需要提供参数,并且因为startsWith方法不接受您尝试谓词的值。您可以编写自己的方法,如:

private static boolean startsWithDash(String text) {
    return text.startsWith("-");
}

...然后使用:

.filter(MyType::startsWithDash)

或者作为非静态方法,您可以:

public class StartsWithPredicate {
    private final String prefix;

    public StartsWithPredicate(String prefix) {
        this.prefix = prefix;
    }

    public boolean matches(String text) {
        return text.startsWith(text);
    }
}

然后使用:

// Possibly as a static final field...
StartsWithPredicate predicate = new StartsWithPredicate("-");
// Then...
List<String> negatives = numbers.stream().filter(predicate::matches)...

但是你可以让StartsWithPredicate实现Predicate<String>并将谓词本身传递给:) {/ p>

相关问题