很抱歉问了这个简单的问题 - 我来自 .NET 堆栈。我想要的只是一个内联谓词。请告诉我我做错了什么:
toReturn = Iterables.find(articles, a -> a.toString().equals(input));
它告诉我“a 无法解析为变量”。我假设我只需要导入或者我正在使用旧版本的 Java?提前致谢!
最佳答案
您想要做的事情在 Java 7 或更早版本中是不可能的;但它存在于 Java 8 及更高版本中。对于 Java 7 及更早版本,您可以使用 lambdaj但达到类似的效果。它看起来像这样:
toReturn = Iterables.find(articles, new Predicate<Object>() {
public boolean apply(Object item) {
return item.toString().equals(input);
}
});
您可以查看更多详情here .
编辑: 正如评论中指出的,还有其他选择。当您使用 Iterables 时我猜你会想要一个 com.google.common.base.Predicate其定义非常相似:
toReturn = Iterables.find(articles, new Predicate<Object>() {
public boolean apply(Object item) {
return item.toString().equals(input);
}
public boolean equals(Object obj) {
// check whether the other object is also a Predicate
}
});
关于Java 内联谓词 : cannot be resolved to a variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20222697/