加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:21:20 所属栏目:Java 来源:网络整理
导读:我有一种方法来验证数字列表中没有负数: private void validateNoNegatives(ListString numbers) { ListString negatives = numbers.stream().filter(x-x.startsWith("-")).collect(Collectors.toList()); if (!negatives.isEmpty()) { throw new RuntimeEx
我有一种方法来验证数字列表中没有负数:

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(“ – ”)但是没有用.

解决方法

不,您不能使用方法引用,因为您需要提供参数,并且因为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>并只是传递谓词本身:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读