Java 如何使用 lambda 表达式检查元素是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23004921/
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 to check if element exists using a lambda expression?
提问by Miljac
Specifically, I have TabPane, and I would like to know if there is element with specific ID in it.
具体来说,我有 TabPane,我想知道其中是否有具有特定 ID 的元素。
So, I would like to do this with lambda expression in Java:
所以,我想用 Java 中的 lambda 表达式来做到这一点:
boolean idExists = false;
String idToCheck = "someId";
for (Tab t : tabPane.getTabs()){
if(t.getId().equals(idToCheck)) {
idExists = true;
}
}
采纳答案by Masudul
回答by jFrenetic
While the accepted answer is correct, I'll add a more elegant version (in my opinion):
虽然接受的答案是正确的,但我会添加一个更优雅的版本(在我看来):
boolean idExists = tabPane.getTabs().stream()
.map(Tab::getId)
.anyMatch(idToCheck::equals);
Don't neglect using Stream#map()which allows to flatten the data structure before applying the Predicate
.
不要忽视使用Stream#map(),它允许在应用Predicate
.
回答by kevinarpe
The above answers require you to malloc a new stream object.
上面的答案要求您 malloc 一个新的流对象。
public <T>
boolean containsByLambda(Collection<? extends T> c, Predicate<? super T> p) {
for (final T z : c) {
if (p.test(z)) {
return true;
}
}
return false;
}
public boolean containsTabById(TabPane tabPane, String id) {
return containsByLambda(tabPane.getTabs(), z -> z.getId().equals(id));
}
...
if (containsTabById(tabPane, idToCheck))) {
...
}