0

My problem is that a collection has a null value, and any "utils" method return that the collection is not empty. There are other "elegant" options?

This code throws a null pointer exception:

 public static void main(String[] args) { ArrayList<String> strings = new ArrayList<>(); strings.add(null); if(CollectionUtils.isNotEmpty(strings)) { for (String s : strings) { System.out.println(s.length()); } } } 
7
  • Welcome to Stack Overflow! Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. Commented Jul 6, 2017 at 22:22
  • 4
    A collection containing null isn't empty. If your collection can contain null, you'll need to check for that when iterating over it. (But 99% of the time you're better off just making it impossible for your collection to contain null.) Commented Jul 6, 2017 at 22:24
  • This isn't a duplicate of stackoverflow.com/questions/34305512/… - the OP here is asking "is there a util method for detecting whether a list contains a null?". Commented Jul 6, 2017 at 22:25
  • Welcome to Java. Really though, you're probably just best off just doing a null check in the loop before trying to access it. Commented Jul 6, 2017 at 22:25
  • @OliverCharlesworth I marked that by accident (I was about to mark that one, and still had it in my copy buffer; the next copy didn't work), and had already changed it to this: stackoverflow.com/questions/33902195/… Commented Jul 6, 2017 at 22:26

1 Answer 1

1

You can check if there are nulls in the collection and/or filter like in the following code:

public static void main(String[] args) { List<String> strings = new ArrayList<>(); strings.add("one"); strings.add(null); strings.add("two"); // has a null value? final boolean hasNulls = strings.stream() .anyMatch(Objects::isNull); System.out.println("has nulls: " + hasNulls); // filter null values strings = strings.stream() .filter(Objects::nonNull) .collect(Collectors.toList()); System.out.println("filtered: " + strings.toString()); } 
Sign up to request clarification or add additional context in comments.

3 Comments

The OP doesn't know how to do a null check and you're showing him stream processing?
@AbhijitSarkar: He was asking for elegant options to check or process a collection which may contain nulls. Of course you could stick with the for loop and add an additional if(s != null)
He had "elegant" in quotes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.