-2

I am trying to filter the list of customer which has purchased online , but I am getting exception here something like this , is there any way to handle it and avoid nullpointer

{
    "timestamp": "2021-08-31T03:30:06.176+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Cannot invoke \"String.equals(Object)\" because the return value of \"com.bhushan.spring.files.excel.model.Productnames.getTypeofcustomer()\" is null",
    "trace": "java.lang.NullPointerException: Cannot invoke \"String.equals(Object)\" because the return value of \"com.bhushan.spring.files.excel.model.Productnames.getTypeofcustomer()\" is null\n\tat com.bhushan.spring.files.excel.controller.StockController.lambda$0(StockController.java:86)\n\tat
    "path": "/api/excel/onlineproductpurchasedstock"
}

This is my code :-

   public List<Productnames> getproductpurchasedlist() {
            List<Productnames> getproducts = stockProductService.getproducts();
            if (getproducts.size() > 0) {
                List<Productnames> collect = getproducts.stream()
                        .filter(i -> i.getTypeofcustomer().equals("ONLINE_CUSTOMER")).collect(Collectors.toList());
                return collect;
            } else {
                return Collections.emptyList();
            }
    
        }
M. Deinum
  • 115,695
  • 22
  • 220
  • 224
  • 2
    It's about coding style you must know. Since the `i.getTypeofcustomer()` is potential null, don't call any method from that type of object. On the other hand, "ONLINE_CUSTOMER" is never null, just use it to call `equals` – Minh Duy Aug 31 '21 at 03:55

1 Answers1

1

just try this,

public List<Productnames> getproductpurchasedlist() {
        List<Productnames> getproducts = stockProductService.getproducts();
        return getproducts.stream()
                .filter(i -> "ONLINE_CUSTOMER".equals(i.getTypeofcustomer())).collect(Collectors.toList());
    }
archzi
  • 369
  • 3
  • 14