Optional Optional - 1 year ago 89
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"));

This works. But is there a way I can use the "referred" parameterized methods like


Answer Source

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"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download