Search code examples
java-8streamflatmap

Null pointer exception while consuming streams


{
   "rules": [
      {
         "rank": 1,
         "grades": [
            {
               "id": 100,
               "hierarchyCode": 32
            },
            {
               "id": 200,
               "hierarchyCode": 33
            }
         ]
      },
      {
         "rank": 2,
         "grades": []
      }
   ]
}

I've a json like above and I'm using streams to return "hierarchyCode" based on some condition. For example if I pass "200" my result should print 33. So far I did something like this:

request.getRules().stream()
        .flatMap(ruleDTO -> ruleDTO.getGrades().stream())
        .map(gradeDTO -> gradeDTO.getHierarchyCode())
        .forEach(hierarchyCode -> {
           //I'm doing some business logic here
           Optional<SomePojo> dsf = someList.stream()
              .filter(pojo -> hierarchyCode.equals(pojo.getId())) // lets say pojo.getId() returns 200
              .findFirst();
           System.out.println(dsf.get().getCode());
        });

So in the first iteration for the expected output it returns 33, but in the second iteration it is failing with Null pointer instead of just skipping the loop since "grades" array is empty this time. How do I handle the null pointer exception here?


Solution

  • You can use the below code snippet using Java 8:

    int result;
    int valueToFilter = 200;
    List<Grade> gradeList = data.getRules().stream().map(Rule::getGrades).filter(x-> x!=null && !x.isEmpty()).flatMap(Collection::stream).collect(Collectors.toList())
    Optional<Grade> optional = gradeList.stream().filter(x -> x.getId() == valueToFilter).findFirst();
    if(optional.isPresent()){
    result = optional.get().getHierarchyCode();
    System.out.println(result);
    

    }

    I have created POJO's according to my code, you can try this approach with your code structure.

    In case you need POJO's as per this code, i will share the same as well.

    Thanks, Girdhar