在Java中检查集合对象是否为空

时间:2020-06-11 08:55:05

标签: java spring

我有一个具有以下结构的Collection对象:

[
  {
    "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
  }
]

我要检查它是否为空:

[
  {}
]

这是我要检查的功能:

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);
        }
    }

与personService.getFamilyTree和personService.getFamilyTree2Gen一起返回集合

我该怎么办?非常感谢,抱歉我的英语不好!

1 个答案:

答案 0 :(得分:0)

使用下面的实用程序方法了解集合是否为空或空。

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);
}

然后像这样在您的代码中写

Collection<Object> familyTree = personService.getFamilyTree(id, gender);
if (isNotEmpty(familyTree)) {
    return familyTree;
} else {
    return personService.getFamilyTree2Gen(id,gender);
}