Mahesh :
Lets say I have a pojo Medicine
,
class Medicine{
private String xmedicine;
private String ymedicine;
private String zmedicine;
//getter and setter here....
}
Below API used to collect medicine if medicine is not null.
public List<Map<String, Object>> gettMedicine(Medicine medicine) {
List<Map<String, Object>> detailsList = null;
List<Integer> list = new ArrayList<>();
if(null != medicine.getXmedicine()){
list.add(medicine.getXmedicine());
}
if(null != medicine.getYmedicine()){
list.add(medicine.getYmedicine());
}
if(null != medicine.getZmedicine()){
list.add(medicine.getZmedicine());
}
if(!CollectionUtils.isEmpty(list)) {
detailsList = //calling other API to get details from list;
}
return detailsList;
}
Is it preferred to use java 8 Optional
here to eliminate NullPointerException
as I have multiple null checks making my code boilerplate.
If yes then can you please suggest how can I use Optional
here?
Adrian :
You should not use Optional
for fields in a class or to replace it with null checks like in your ifs. In this case you can do the following:
Stream.of(medicine.getXmedicine(), medicine.getYmedicine(), medicine.getZmedicine())
.filter(Objects::nonNull)
.collect(Collectors.toList())