1

I have a Collection Object with structure like this:

[
  {
    "maBN": 8,
    "address": "American",
    "_type": "Person",
    "name": "Anna Johnson",
    "parent_of": [
      {
        "maBN": 10,
        "address": "American",
        "_type": "Person",
        "name": "Abraham Napoleon",
        "parent_of.type": "natural",
        "_id": 63
      },
      {
        "maBN": 11,
        "address": "American",
        "_type": "Person",
        "name": "William Napoleon",
        "parent_of.type": "natural",
        "_id": 64
      }
    ],
    "_id": 61
  }
]

I want to check if it null like this:

[
  {}
]

This is my function to check it:

public Collection<Object> getFamilyTree(@RequestParam Long id, @RequestParam String gender) {
        if (personService.getFamilyTree(id,gender).toArray().length!=0)
        {
            return personService.getFamilyTree(id, gender);
        }
        else{
            return personService.getFamilyTree2Gen(id,gender);
        }
    }

With personService.getFamilyTree and personService.getFamilyTree2Gen return a Collection

What should I do? Thanks a lot and sorry for my bad English!

An Duy
  • 35
  • 1
  • 7
  • 2
    Does this answer your question? [Best practice to validate null and empty collection in Java](https://stackoverflow.com/questions/12721076/best-practice-to-validate-null-and-empty-collection-in-java) – deadshot Jun 11 '20 at 08:59

1 Answers1

0

Use below utility method to know if the collection null or empty.

public static <T> boolean isEmpty(Collection<T> c) {
   if (c == null) {
       return true;
   } else {
       return c.size() == 0;
   }
}

public static <T> boolean isNotEmpty(Collection<T> c) {
   return !isEmpty(c);
}

Then Write in your code like this

Collection<Object> familyTree = personService.getFamilyTree(id, gender);
if (isNotEmpty(familyTree)) {
    return familyTree;
} else {
    return personService.getFamilyTree2Gen(id,gender);
}
Sahil Garg
  • 167
  • 6
  • A more idiomatic way to check of a non-null collection is empty would be `c.isEmpty()`. I would hesitate to call these methods "is empty" and "is not empty", given that there is already a well-known notion of "emptiness" of Java collections: "is null or empty" would be better. – Andy Turner Jun 11 '20 at 09:09
  • @AndyTurner I agree with you. but calling `c.isEmpty()` on a null collection will produce NullPointerException which I guess is not desired in this case. – Sahil Garg Jun 11 '20 at 09:16
  • 1
    hence "on a non-null collection". Don't use size, use isEmpty. – Andy Turner Jun 11 '20 at 09:17
  • this is the implementation of isEmpty() from java.util `public boolean isEmpty() { return size() == 0; }` – Sahil Garg Jun 11 '20 at 09:19
  • yes; but consider why there is a need for the `isEmpty()` method as well: the `isEmpty()` method allows for implementations of `Collection` to short-circuit size evaluation, e.g. if would require traversing a linked list. – Andy Turner Jun 11 '20 at 09:32