如何否定方法引用谓词 [英] How to negate a method reference predicate

查看:175
本文介绍了如何否定方法引用谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 8中,您可以使用方法引用来过滤流,例如:

In Java 8, you can use a method reference to filter a stream, for example:

Stream<String> s = ...;
long emptyStrings = s.filter(String::isEmpty).count();

有没有办法创建一个方法引用,它是对现有方法的否定,即类似:

Is there a way to create a method reference that is the negation of an existing one, i.e. something like:

long nonEmptyStrings = s.filter(not(String::isEmpty)).count();

我可以创建而不是方法,如下所示但我想知道JDK是否提供类似的东西。

I could create the not method like below but I was wondering if the JDK offered something similar.

static <T> Predicate<T> not(Predicate<T> p) { return o -> !p.test(o); }


推荐答案

java-11 提供了一种新方法谓词#不

所以你可以否定方法参考:

So you can negate the method reference:

Stream<String> s = ...;
long nonEmptyStrings = s.filter(Predicate.not(String::isEmpty)).count();

这篇关于如何否定方法引用谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆