0

I have a list of a bean class newSRMAPIResponseBeanList wherein I am always getting a null object at last which I am trying to remove but it is resulting in null pointer exception if I handle the exception, it is not removing that null value. Below is my code.

for (int i = 0; i < newSRMAPIResponseBeanList.size(); i++) {
                try {
                    if (newSRMAPIResponseBeanList.get(i).getCompanyId().equals(null)) {
                        newSRMAPIResponseBeanList.remove(i);
                    }
                }catch(Exception e) {
                    e.printStackTrace();
                }
            }

In the if condition itself it is failing. I want to remove the null value of company ID. Actually newSRMAPIResponseBeanList is a list of List<NewSRMAPIResponseBean> newSRMAPIResponseBeanList = new ArrayList<>(); and the bean class is as follows.

public class NewSRMAPIResponseBean {
    private String companyId;
    private String investmentId;
    private String performanceId;
    private List<String> values;
}

Is there any way I can remove that null value? I also tried using Java streams as follows.

List<NewSRMAPIResponseBean> finalList=newSRMAPIResponseBeanList.parallelStream()
                  .filter(Objects::nonNull)
                  .collect(Collectors.toList());

This too did not work.

Pratik
  • 33
  • 7
  • Please post the complete error-output (including stack trace) for "resulting in null pointer exception", also show what did not work when filtering with Java's Streaming API. – hc_dev Feb 17 '23 at 20:05

1 Answers1

0

I want to remove the null value of company ID.

I presume you mean remove the list element if the Id is null. So It's not the bean that is null, it is the companyId. Assuming you have getters, try it like this. If the Id is not null, let it pass thru.


List<NewSRMAPIResponseBean> finalList=newSRMAPIResponseBeanList.parallelStream()
        .filter(bean->bean.getCompanyId() != null)
        .collect(Collectors.toList());

You can also do it in a simple loop. To avoid a ConurrentModificationException, use an iterator.

Iterator<NewSRMAPIResponseBean> iter =  newSRMAPIResponseBeanList.iterator();
while (iter.hasNext()) {
    if (iter.next().getCompanyId() == null) {
        iter.remove();
    }
}
WJS
  • 36,363
  • 4
  • 24
  • 39