javajpaarraylistspring-data-jpajpa-criteria

How to filter null values in ArrayList


I have a very big code. I faced an issue where at very starting of code, null gets inserted inside arraylist custlist i.e custlist looks like [null]. And after many lines of code, I had my code changes where I was building up Predicate using custlist as shown below:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Customer> q = cb.createQuery(Customer.class);

Root<Customer> root = q.from(Customer.class);
q.select(root);
if (!CollectionUtils.isEmpty(custlist)){
Predicate predicate1 =root.get("custid").in(custlist);
}

q.where(predicate1);
TypedQuery<Customer> tq = em.createQuery(q);
List<Customer> allcust= tq.getResultList();

So the first check gets passed since (custlist != null && !custlist.isEmpty()) and predicate was built up. This gave me error when final query is being executed.My question is - is there anyway by which I can make sure that predicate is only created when custlist doesn't have null values. My ask is - Just like Collectionutils.isEmpty() makes a check for null & emptyness simultaneously , if anyone can help me with some API that can also check null inside arraylist as well.


Solution

  • Here a generic solution :

    private static ArrayList<String> list = new ArrayList<String>();
    public static void main(String[] args) {
        list.add("foo");
        list.add("bar");
        if (!list.isEmpty() && !list.contains(null))
            System.out.println("ok");
        list.add(null);
        if (!list.isEmpty() && !list.contains(null))
            System.out.println("not ok");
    }
    

    result

    ok