0

The answer from a library (DBpediaLookupClient.variableBindings()) results in

List<Map<String, String>>

I am trying to check is if the list if empty or not. What I have tried so far is

if (dbpedialookup.variableBindings() != null && !dbpedialookup.variableBindings().isEmpty()) {
    System.out.println("Results Present);
} else {
    System.out.println("No Results");
}

But, on items where the resultant List is []. Its throwing,

Exception in thread "main" java.lang.NullPointerException

How do we check for null in such a situation?

Lahiru Ashan
  • 602
  • 9
  • 16
Betafish
  • 990
  • 3
  • 14
  • 33
  • How do you test resultant that resultant List is [] if it is throwing an Exception? I suggest you check references one after another. – Witold Kaczurba Oct 28 '16 at 05:21
  • 2
    The check for `variableBindings()` not returning `null` and testing `isEmpty()` only if `variableBindings()` does not return `null` looks correct. The only viable alternative is that `dbpedialookup` is `null`. Please add this check too. – Thomas Kläger Oct 28 '16 at 05:27

3 Answers3

2

Look like the top object is null so

if (dbpedialookup != null && 
    dbpedialookup.variableBindings() != null &&
   !dbpedialookup.variableBindings().isEmpty()) {
Scary Wombat
  • 41,782
  • 5
  • 32
  • 62
1

The following is the pattern:

if (myList != null && !myList.isEmpty()) {
    System.out.println("Isn't empty");
} else {
    System.out.println("Is empty");
}

If you want to check variables in the list use the following:

if (myList != null) {
    for (Map<String, String> map : myList) {
        if (map != null) {
            //perform on map
        }
    }
}
xenteros
  • 14,275
  • 12
  • 47
  • 81
0

Use Optional to tidy things up:

if (Optional.ofNullable(dbpedialookup).map(DBpediaLookupClient::variableBindings).map(List::isEmpty).orElse(true))
    // it's empty / null
Bohemian
  • 365,064
  • 84
  • 522
  • 658
  • I'm not sure I agree that that's tidier than Scary Wombat's approach; but even if it is, I feel confident that this answer won't actually help the OP understand what the problem was. – ruakh Oct 28 '16 at 05:34