0

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
    })
);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Vipercold
  • 599
  • 1
  • 7
  • 27

3 Answers3

4

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:

  • throw an exeption. For example if a method's input causes a division by zero you can throw an exception instead of returning null.
  • return an empty Optional. For example a method returning String could be changed to return Optional<String>. When there is no String to return, you return Optional.empty()
  • return an empty Collection (e.g. when the result type is a List, return an empty List if there are no results found, rather than returning null)
  • return a custom result type, capable of reflecting the result. For example when doing validation you could return a ValidationResult representing success/failure and error messages instead of returning a null error message when there is no error
Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
3
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.

Lothruin
  • 3
  • 3
Steven Waterman
  • 611
  • 4
  • 17
  • Is the .filter(discount - discount != null) necessary? Doesn't .map(discount->discount.getPromotions()) do the job? – Vipercold Dec 12 '16 at 21:05
  • 1
    If item.getDiscount() returned null then you'd get a NPE when doing .map(discount.getPromotions()) unless you filter out the null discount values first – Steven Waterman Dec 12 '16 at 21:07
  • 2
    I would argue that the Discount class should be designed to *never* return null from a collection method like getPromotions; when there are zero promotions, always return an empty collection. – VGR Dec 12 '16 at 22:18
  • Perfect answer so that foreach doesn't throw null pointer exception. – AdityaKapreShrewsburyBoston Mar 07 '21 at 20:53
3

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