1

I wrote bellow code to check some condition.

/**
 * Returns true if any of the dose detail is an x
 * @return boolean
 */
public <DD extends BD<DI>, DI extends BI> boolean Y(final Collection<DD> dds) {
    return dds.stream().anyMatch(dd -> dd.M().K());
}

but this method have some risk dds , come as null. I need to return false is dd also null. how can be modify this method using java 8 to null safe ?

4 Answers 4

7

Or you can do like this. More or like the same way

return dds != null && dds.stream().anyMatch(dd -> dd.M().K());
2

Alternatively, you can wrap it around an Optional as:

public <DD extends BD<DI>, DI extends BI> boolean Y(final Collection<DD> dds) {
    return Optional.ofNullable(dds)
            .filter(d -> d.stream().anyMatch(dd -> dd.M().K()))
            .isPresent();
}
2

It could be as simple as

public <DD extends BD<DI>, DI extends BI> boolean Y(final Collection<DD> dds) {
    return dds == null ? false : dds.stream().anyMatch(dd -> dd.M().K());
}
1
  • 2
    You never need to combine literal true or false with another boolean expression; there’s always an alternative without it. Here, it’s just return dds != null && dds.stream().anyMatch(dd -> dd.M().K());
    – Holger
    Commented May 9, 2019 at 10:16
1

I like the answer from @the_tech_maddy. Just a preferred way to check a collection is null or empty from org.apache.commons.collections.CollectionUtils;

return CollectionUtils.isNotEmpty(dds) && dds.stream().anyMatch(dd -> dd.M().K());

Not the answer you're looking for? Browse other questions tagged or ask your own question.