0

Is there any collection in java that won't add null object? Given a list of item, query DB for those items, when the result returned from DB, i'll add the item to result list if it does exist in DB, if it doesn't DB return null, then I'll discard it.

I have following code does this:

reqIds.forEach(
        reqId -> {
          columnValueMap.clear();
          columnValueMap.put("request_id", reqId);
          EventAudit auditRecord =
              pollDatabaseFindByIdAndKey(
                  EventAudit.class, columnValueMap);

          if (auditRecord != null) {
            auditMap.put(auditRecord.getRequestId(), auditRecord);
          }
        });

i know i can use Java stream filter to filter out null but just wonder if there is any smart collection that will reject null object automatically so i don't need to do extra Null checking

Bucket
  • 7,415
  • 9
  • 35
  • 45
user468587
  • 4,799
  • 24
  • 67
  • 124
  • 1
    you can use external libraries such as `google guava` or `apache commons`, please look at https://stackoverflow.com/questions/6433478/is-there-a-standard-java-list-implementation-that-doesnt-allow-adding-null-to-i – nader.h May 29 '19 at 15:17
  • 1
    Nothing you'd want. Only collections that throw exceptions when you try to add `null`. It's also not a good idea to implement such a collection since silently discarding data is not obvious behavior while `if (foo != null) add (foo)` makes it clear what happens. – zapl May 29 '19 at 15:20
  • Looks like you need a Map. According to https://github.com/google/guava/wiki/LivingWithNullHostileCollections `ConcurrentHashMap` does not allow `null`s – bracco23 May 29 '19 at 15:20
  • @Sunchezz Are you sure you'll get a set without null objects? Javadocs explicitely states: "This class permits the null element" – Robert Kock May 29 '19 at 15:21
  • @RobertKock you are right. removed my comment. Don't know where this knowledge came from :( Thought i read this somewhere... – Sunchezz May 29 '19 at 15:27
  • Maybe there are also good answers [here](https://stackoverflow.com/questions/4819635/how-to-remove-all-null-elements-from-a-arraylist-or-string-array/15381271) – Sunchezz May 29 '19 at 15:36

2 Answers2

0

You can use apache commons collection to do this,

import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.PredicateUtils;
import com.google.common.collect.Lists;

public class Test {
    public static void main(String[] args) {
        List<Integer> l = Lists.newArrayList(1, 2, 3, null, 7, null, 8, null);
        CollectionUtils.filter(l, PredicateUtils.notNullPredicate());
        System.out.println(l);
    }
}

above code will print output as like,

[1, 2, 3, 7, 8]
Nithyananth
  • 74
  • 10
0

Look at the java-doc of Collection and it's definition of add:

If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.

and

NullPointerException - if the specified element is null and this collection does not permit null elements

As you can see such a Collection would break the contract defined in the Collection interface. You will have to look for third party libraries to accomplish what you want but I highly recommend you to not use such a collection as it breaks several assumption an the principle of least astonishment when a user comfortable with other collections gets unexpected behaviour.

roookeee
  • 1,710
  • 13
  • 24