Creating a shared predicate in Java 8

I am new to Java 8 and wanted to know if it is possible to pass instance methods to another method, which in turn calls it using the lambda parameter:

Consider this class:

import java.util.function.Predicate;

public class PredicateTest {

    private class SomeType {

        public boolean bar() {
            return true;
        }

        public boolean foo() {
            return true;
        }
    }

    public void someMethod() {
        Predicate<SomeType> firstPredicate = someType -> someType.bar();
        Predicate<SomeType> secondPredicate = someType -> someType.foo();
        //...
    }

    public Predicate<SomeType> getGenericPredicate(/* ?? what goes here ?? */) {
        Predicate<SomeType> predicate = someType -> someType./* ?? how to call passed instance method foo or bar? */
        return predicate;
    }
}

The someMethod()two predicates are created SomeType.

If SomeTypeit has 20 methods, perhaps we need to write 20 similar predicates.

I am wondering if it is possible using Java 8 to avoid code duplication using a type method getGenericPredicatethat can take bar()either foo()as a parameter and returns the correct predicate.

The goal is to reorganize someMethodinto something like this:

public void someMethodRefactored() {
        Predicate<SomeType> firstPredicate = getGenericPredicate(SomeType::bar());
        Predicate<SomeType> secondPredicate = getGenericPredicate(SomeType::foo());
        //...
}
+4
1

, getGenericPredicate,

public void someMethodRefactored() {
    Predicate<SomeType> firstPredicate = getGenericPredicate(SomeType::bar());
    Predicate<SomeType> secondPredicate = getGenericPredicate(SomeType::foo());
    //...
}

public void someMethodRefactored() {
    Predicate<SomeType> firstPredicate = SomeType::bar;
    Predicate<SomeType> secondPredicate = SomeType::foo;
    //...
}

, getGenericPredicate (, ),

public <T> Predicate<T> getGenericPredicate(Predicate<T> p) {
    //some additional code goes here
    return p;
}

public void someMethodRefactored() {
    Predicate<SomeType> firstPredicate = getGenericPredicate(SomeType::bar);
    Predicate<SomeType> secondPredicate = getGenericPredicate(SomeType::foo);
    //...
}
+5

All Articles