我有一个整数流,我想找到两个数字之和等于另一个数字。所以我想出了以下解决方案:
BiPredicate<Integer, Integer> p = (price1, price2) -> price1.intValue() + price2.intValue() == moneyQty;
flavoursPrices.filter(p);
但是filter方法没有接收到一个BiPredicate。为什么不?有什么替代方案?
最佳答案
您仍然可以使用 Bipredicate。 filter-method 需要的参数是一个 Predicate,下面是一个如何使用这个 BiPredicate 的例子:
BiPredicate<Integer, Integer> p = (price1, price2) -> price1.intValue() + price2.intValue() == moneyQty;
flavoursPrices.stream().filter(el->p.test(el.price1,el.price2));
在此示例中,flavoursPrices 必须是一个列表。
我们正在使用的 lambda:
el->p.test(el.price1,el.price2)
正在替换匿名内部类声明以从 BiPredicate 中创建新的 Predicate:
Predicate<Integer> arg =new Predicate<Integer>() {
@Override
public boolean test(Element el) {
return p.test(el.price1,el.price2);
}
};
因此,为了过滤流,我们为来自流的每个元素创建一个新的 Predicate,然后我们使用这个 Predicate 作为参数来使用它的测试方法。这样做的一大优势是,我们不必提前创建大量谓词,但我们可以传递 lambda 函数中的每个元素并获取它的属性。
关于Java 8 - 使用 BiPredicate 进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36020736/