I am trying to write a filtering predicate that will filter a list based on a value held in a different object, but the object that I want to extract the value to compare against is available at the time that the comparison is carried out, not at the time the predicate is defined.
Here's an SSCCE
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class StreamTest {
public static void main(String [] args){
DataContainer dc = new DataContainer();
Predicate<Integer> p = new Predicate<Integer>(){
@Override
public boolean test(Integer t) {
/********************************************/
return t > 6; // I need this to be t > the limitValue that is available when the predicate gets executed
/********************************************/
}
};
System.out.println(dc.numberOfValuesGreaterThan(p, new LimitValue(6)));
}
}
class DataContainer{
private List<Integer> l = Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9,10});
public long numberOfValuesSatisfyingPredicate(Predicate predicate,LimitValue lv){
return l.stream()
.filter(predicate)
.count();
}
}
class LimitValue{
private int limitValue;
public LimitValue(int limitValue){
this.limitValue = limitValue;
}
public int getValue(){
return limitValue;
}
}
The code creates a DataContainer, that contains the numbers 1 - 10 and has a method that takes a Predicate and a Limit Value, allowing you to do things like get the number of elements greater than 5, or less that 9 by supplying different predicates.
However, at the time the Predicate is defined the LimitValue object is not in scope. Is it possible to define a Predicate that can access variables that are available at execution time but not at definition time?