I am trying to use an object's method in a Java stream to set the filter. For example:
//Full of Test objects that have a method getPredicate() that returns a valid predicate (ex d -> d.getName.equals("Test")).
ArrayList<Test> testArray = new ArrayList<Test>();
testArray
.stream()
.filter(*CURRENTELEMENT*.getPredicate()) //Goal
.forEach(System.out::println);
The return lambda from getPredicate() could be anything as the goal of this is to have a dynamic filter that can be set by the Test objects in this case.
Thanks in advance for any help! This is my first post so I hope I explained myself ok.
Edit/Update: Here is what the getPredicate() method looks like for a Test object:
public Predicate<Test> getPredicate(String name, String id) {
List<Predicate<Test>> allFilters = Arrays.asList();
Predicate<Test> aggregateFilters;
allFilters.add(d -> d.getName().equals(name));
allFilters.add(d -> d.getId().equals(id));
//Chain all filter predicates together using "or" method.
aggregateFilters= allFilters
.stream()
.reduce(d -> false, Predicate::or);
// Returns a valid filter lambda expression
// If I wasn't trying to get the aggregateFilters variable from this method, I could
// statically assign it and plug it right in and it works. ex. .filter(aggregateFilters)
return aggregateFilters;
}
Thanks again for your time and help.
getPredicate()return? It sounds like you just wante -> e.getPredicate().test(e).Testlook like at least and why do you think you need this dynamic setting of aPredicate. this might be an interesting question, but its just poorly written.Predicateif you want to use that return value as a predicate in the filter above. Furthermore, since eachTestobject is returning a predicate, then each time that object is tested against the predicate, it will always be true...wat?