I have this piece of code and i'm trying to figure out what's the best way to avoid null pointer exception using Java 8?
promotion.forEach(item ->
item.getDiscount().getPromotions().forEach(promotion -> {
// logic code here
})
);
I have this piece of code and i'm trying to figure out what's the best way to avoid null pointer exception using Java 8?
promotion.forEach(item ->
item.getDiscount().getPromotions().forEach(promotion -> {
// logic code here
})
);
The best way to avoid NullPointerExceptions is to avoid null values. In your example, make sure all the methods never return null.
Instead of returning null you have several options:
promotion.stream()
.map(item->item.getDiscount()).filter(Objects::nonNull)
.map(discount->discount.getPromotions()).filter(Objects::nonNull)
.forEach(innerPromotion->{//logic code});
You can filter all the null elements out before you use them in the logic code so that only the non-null elements have the logic code run.
Are you thinking about something like Optional :
item.getDiscount().getPromotions().stream().forEach(promotion ->
Optional.ofNullable(promotion).ifPresent(p -> {
// logic code
} )
);
EDIT : if item.getDiscount()
may be null then you can try :
Optional.ofNullable(item.getDiscount()).ifPresent(d ->
d.getPromotions().stream().forEach(promotion ->
Optional.ofNullable(promotion).ifPresent(p -> {
// logic code
} )
)
);