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()); 
Sign up to request clarification or add additional context in comments.

Comments

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(); } 

Comments

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 Comment

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());
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()); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.