I'm pretty new to lambdas and Java8 in general, so I apologize if this is a straightforward question.
I currently have a class that I want to do some intricate matching on that's final, with a bunch of getters:
public final class Foo {
public String getName();
public Type getType();
public List<Bar> getBarList();
....
}
I've written a small helper class for matching:
public class MatchParameter<T> {
boolean expectMatch = true;
T valueToCheck;
public MatchParameter(T value, boolean shouldMatch) {
this.expectMatch = shouldMatch;
this.valueToCheck = value;
}
public boolean matches(Predicate<T> matcher) {
return matcher.test(valueToCheck) == expectMatch;
}
}
I then have a place that creates various MatchParameters for things like checking the name, or checking that a the List<Bar> contains a particular Bar:
MatchParameter<String> nameParam = new MatchParameter(inputName, shouldMatch);
MatchParameter<Bar> barParam = new MatchParameter(inputBar, shouldMatch);
....
I'm currently stuck remembering what each MatchParameter is looking for. Eventually my check code looks like:
if(nameParam.matches(name -> currentFoo.getName().matches(name)) {
...
}
if(barParam.matches(bar -> currentFoo.getBarList().contains(bar)) {
...
}
...
In every case, the Predicate I'm passing is a lambda that has some iteration of currentFoo.<accessorFns> which eventually take a type T, and returns a boolean. What I'd really like to do is move the logic for the accessors to the creation of the MatchParameter.
Is there a way I can specify a function pointer that I can pass in at construction time? I'd expect it to be some sort of runnable that takes a (Foo,T).
In C++ I'd add a local function pointer that took two inputs, a Foo and a T, to MatchParameter's local variables:
bool (*checkFn)(Foo f, T input);
Then I could create an anonymous function for each instantiation, and update my MatchParameter matches implementation to be:
public boolean matches(Foo f) {
return checkFn(f, valueToCheck) == expectMatch;
}
And my instantiation to be:
MatchParameter<String> nameParam = new MatchParameter<>(
inputName,
shouldMatch,
(Foo f, String input) -> boolean { return f.getName().matches(input); }
);
Is there equivalent way to achieve this in Java?