Search code examples
javalambdapredicatefunctional-interface

No access to a parameter needed in a predicate


I have the following two methods method1 and method2 :

public void method1(){
List<Integer> p = ...

listRefCtl.forEach(x->
                    x.getDomains().forEach(domain ->
                            domaine.getRisks().forEach(risk ->
                                    attribution.getFicheControles().removeIf(fc ->
                                                            !DateUtil.isBetween(fc.getT().getDateT(), p.get(0), p.get(1)))))
                            )
                    )
            );
}


public void method2(){
List<Integer> p = ...

listRefCtl.forEach(x->
                    x.getDomains().forEach(domain ->
                            domaine.getRisks().forEach(risk ->
                                    attribution.getFicheControles().removeIf(fc ->
                                                            !DateUtil.isAfter(date1, date2)))
                            )
                    )
            );
}

As you can see, it's the same piece of code except that i have two different predicates inside the removeIf method which are :

!DateUtil.isBetween(fc.getT().getDateT(), p.get(0), p.get(1))

and

!DateUtil.isAfter(date1, date2)

i would like to extract a method like this

public void method1(){
    List<Integer> p = ...
    extractedMethod(() -> !DateUtil.isBetween(fc.getT().getDateT(), p.get(0), p.get(1)));
}

public void method2(){
    List<Integer> p = ...
    extractedMethod(() -> !DateUtil.isAfter(date1, date2));
}

public void extractedMethod(predicate){
listRefCtl.forEach(x->
                    x.getDomains().forEach(domain ->
                            domaine.getRisks().forEach(risk ->
                                    attribution.getFicheControles().removeIf(predicate)))
                            );
}

the problem is that i don't know how to pass the "fc" object in the "extractedMethod" ?

Thank you in advance.


Solution

  • removeIf() takes a Predicate<? super E>, where E is whatever type is in the collection returned by getFicheControles(). For the sake of this answer, let that be Foo.

    public void method1() {
        List<Integer> p = ...
        extractedMethod(fc -> !DateUtil.isBetween(fc.getT().getDateT(), p.get(0), p.get(1)));
    }
    
    public void method2() {
        List<Integer> p = ...
        extractedMethod(fc -> !DateUtil.isAfter(date1, date2));
    }
    
    public void extractedMethod(Predicate<Foo> filter) {
        listRefCtl.forEach(x->
                x.getDomains().forEach(domain ->
                        domaine.getRisks().forEach(risk ->
                                attribution.getFicheControles().removeIf(filter)
                                )));
    }