I am trying to write a filter predicate for Objects.nonNull
and equalsIgnoreCase
, but I am not able to create a predicate for the equalsIgnoreCase
part. Can I have some suggestions?
My code is :
basicDetailEntity.forEach(prj -> {
CharlieAddress billToAddress = addressList.stream()
.filter(add -> Objects.nonNull(add.getSiteDuns())
&& add.getSiteDuns().equalsIgnoreCase(prj.getBillToDuns())
&& Objects.nonNull(add.getOrgName())
&& add.getOrgName().equalsIgnoreCase(prj.getOperatingUnit()))
.findFirst().orElse(null);
I have created the two predicates for the nonNull part, but I'm finding it difficult to create them for the equalsIgnoreCase
one, any suggestion will help.
public static final Predicate<CharlieAddress> CHARLIE_ADDRESS_DUNS_PRESENT =
add -> Objects.nonNull(add.getSiteDuns());
public static final Predicate<CharlieAddress> CHARLIE_ADDRESS_ORG_PRESENT =
add -> Objects.nonNull(add.getOrgName());
The problem is that your condition relies upon two arguments. You need the address and you need the prj (project? -- the rest of this answer assumes so).
add.getSiteDuns().equalsIgnoreCase(prj.getBillToDuns())
^ ^
A predicate takes a single argument and returns a boolean, so unless you have a lambda that acts as a closure which captures some variable from the enclosing scope (which if you want the predicate to be a static field, you probably do not) then what you're asking for is not possible
final Project prj = /*something*/; // must be final or "effectively final"
Predicate<CharlieAddress> foo =
add -> add.getSiteDuns().equalsIgnoreCase(prj.getBillToDuns());
// ^ captured
There is another interface, BiPredicate which takes 2 arguments. Maybe that's what you're looking for.
BiPredicate<CharlieAddress, Project> foo =
(add, prj) -> add.getSiteDuns().equalsIgnoreCase(prj.getBillToDuns());
You didn't ask but your existing predicates can be simplified with != null
public static final Predicate<CharlieAddress> CHARLIE_ADDRESS_DUNS_PRESENT =
add -> add.getSiteDuns() != null;
public static final Predicate<CharlieAddress> CHARLIE_ADDRESS_ORG_PRESENT =
add -> add.getOrgName() != null;