[英]java-8 Predicated with parameter
For java8 in action example :: https://github.com/java8/Java8InAction/blob/master/src/main/java/lambdasinaction/chap1/FilteringApples.java 对于Java8实际示例:: https://github.com/java8/Java8InAction/blob/master/src/main/java/lambdasinaction/chap1/FilteringApples.java
public static boolean isGreenApple(Apple apple),
public static boolean isHeavyApple(Apple apple) {
I want to add a similar method eg 我想添加类似的方法,例如
public static boolean isAppleOfColor(Apple apple, String color)
And i want to access it using same pattern :: 我想使用相同的模式访问它:
List<Apple> colorApples = filterApples(inventory, FilteringApples::isAppleOfColor("red"));
But I can't pass arguments in FilteringApples::isAppleOfColor("red"). 但是我不能在FilteringApples :: isAppleOfColor(“ red”)中传递参数。
So far I have achieved this using following : 到目前为止,我已经使用以下方法实现了这一点:
public static Predicate<Apple> colourMatches( String color) {
return p->color.equals(p.getColor());
}
and then calling 然后打电话
List<Apple> colorApples = filterApples(inventory, (Apple a)->a.colourMatchesOnApple("red"));
System.out.println(colorApples);
This works. 这可行。 But is there a way I can use the "referred" parameterized methods like
FilteringApples::isAppleOfColor("red").
但是有没有一种方法可以使用
FilteringApples::isAppleOfColor("red").
类的“引用”参数化方法FilteringApples::isAppleOfColor("red").
thanks 谢谢
EDIT 编辑
Thanks All, I just realized in JLS 15.13 : https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.13 as following text: 谢谢,我刚刚在JLS 15.13中实现: https : //docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.13 ,如下所示:
It is not possible to specify a particular signature to be matched, for example, Arrays::sort(int[]).
无法指定要匹配的特定签名,例如Arrays :: sort(int [])。 Instead, the functional interface provides argument types that are used as input to the overload resolution algorithm (§15.12.2).
而是,功能接口提供了用作过载解析算法(第15.12.2节)的输入的参数类型。 This should satisfy the vast majority of use cases;
这应该满足绝大多数用例; when the rare need arises for more precise control, a lambda expression can be used.
当极少数需要进行更精确的控制时,可以使用lambda表达式。
Method reference cannot capture additional variables. 方法参考无法捕获其他变量。
What you can do is 你能做的是
List<Apple> colorApples = filterApples(inventory, a -> isAppleOfColor(a, "red"));
which you will note is shorter. 您会注意到它较短。
Note: I would avoid using a static
method esp when the first argument is a type you are writing. 注意:当第一个参数是您正在编写的类型时,我将避免使用
static
方法esp。 Much better to add 更好地添加
// added to Apple
public boolean isColor(String color)
and you can call 你可以打电话
List<Apple> colorApples = filterApples(inventory, a -> a.isColor("red"));
which is likely to be the same as 这可能与
List<Apple> colorApples = inventory.stream()
.filter(a -> a.isColor("red"))
.collect(toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.