Optional Optional - 23 days ago 7
Java Question

java-8 Predicated with parameter

For java8 in action example :: 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 e.g

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").

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").


thanks

Answer

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. 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());