java 如何否定 lambda 谓词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28235764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I negate a lambda Predicate?
提问by Jin Kwon
Lets say I have a Stream of Strings.
假设我有一个字符串流。
final Stream<String> stream = ...;
I want to filter out each empty string after trimmed.
我想在修剪后过滤掉每个空字符串。
stream
.filter(Objects::nonNull)
.map(String::trim)
.filter(v -> !v.isEmpty());
Is there any way to apply Predicate#negate()for replacing v -> !v.isEmpty()
part?
有没有办法应用Predicate#negate()来替换v -> !v.isEmpty()
部分?
.filter(((Predicate) String::isEmpty).negate()) // not compile
回答by Misha
You would have to do .filter(((Predicate<String>) String::isEmpty).negate())
你必须做 .filter(((Predicate<String>) String::isEmpty).negate())
If you want, you can define
如果你愿意,你可以定义
static<T> Predicate<T> not(Predicate<T> p) {
return t -> !p.test(t);
}
and then
接着
.filter(not(String::isEmpty))
but I would just stick with v -> !v.isEmpty()
但我会坚持下去 v -> !v.isEmpty()
回答by tobias_k
It seems like you have to cast to Predicate<String>
for this to work:
似乎你必须投射到Predicate<String>
这个才能工作:
.filter(((Predicate<String>) (String::isEmpty)).negate())
Of course, it would be much shorter to use a lambda in this case:
当然,在这种情况下使用 lambda 会更短:
.filter(s -> ! s.isEmpty())