Java thread assigns filter predicate from element method

I am trying to use an object method in a Java thread to set a filter. For instance:

//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 () may be something else, since the purpose of this is to have a dynamic filter that can be set by Test objects in this case.

Thanks in advance for your help! This is my first post, so I hope I will explain it myself.

Edit / Update: This is what the getPredicate () method looks like for the 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.

+4
source share
1 answer

You can do:

testArray.stream().filter(e -> e.getPredicate("some_name", "some_id").test(e)).forEach(System.out::println);

where is Testdefined as in your question.

, getPredicate Test, - . , :

testArray.stream().filter(e -> Test.getPredicate("some_name", "some_id").test(e)).forEach(System.out::println);

: , Arrays.asList(), UnsupportedOperationException add, . new ArrayList<>().

+1

Source: https://habr.com/ru/post/1695721/


All Articles