【问题标题】:Checking if a collection is null or empty in Groovy在 Groovy 中检查集合是否为空或为空
【发布时间】:2013-06-19 20:39:28
【问题描述】:

我需要对集​​合执行 null 或空检查;我认为!members?.empty 是不正确的。有没有更时髦的方法来编写以下内容?

if (members && !members.empty) {
    // Some Work
}

【问题讨论】:

    标签: grails groovy


    【解决方案1】:

    确实有 Groovier Way。

    if (members) {
        //Some work
    }
    

    如果members 是一个集合,则执行所有操作。空检查和空检查(空集合被强制为false)。冰雹Groovy Truth。 :)

    【讨论】:

    • 一种更“时髦”的方式是,例如,如果您对成员的最大年龄感兴趣,那么您可以编写以下内容:members?.age.max()
    • 注意:members?.age.max() 在成员为 null 时会出现“无法在 null 对象上调用方法 max()”。你需要members?.age?.max()
    • @VinodJayachandran 是的
    • 否:GreenGiant 的解决方案是最好的:针对这两种解决方案检查 List members = null;List members = [ [age: 12], [age: 24], [age: null], null ]
    • 这种类型的检查适用于大多数情况,但如果您的目的是检查变量是否为空,那么您可能会遇到变量不为空而是布尔值 false 的边缘情况
    【解决方案2】:

    仅供参考,这种代码可以工作(你会觉得它很丑,这是你的权利:)):

    def list = null
    list.each { println it }
    soSomething()
    

    换句话说,这段代码有空/空检查both没用:

    if (members && !members.empty) {
        members.each { doAnotherThing it }
    }
    
    def doAnotherThing(def member) {
      // Some work
    }
    

    【讨论】:

      【解决方案3】:
      !members.find()
      

      我认为现在解决这个问题的最好方法是上面的代码。它从 Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find() 开始工作。例子:

      def lst1 = []
      assert !lst1.find()
      
      def lst2 = [null]
      assert !lst2.find()
      
      def lst3 = [null,2,null]
      assert lst3.find()
      
      def lst4 = [null,null,null]
      assert !lst4.find()
      
      def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
      assert lst5.find() == 42
      
      def lst6 = null; 
      assert !lst6.find()
      

      【讨论】:

      • 有1个空元素的集合不为空,所以你的建议是错误的
      • 如果集合为空怎么办?
      • def lst6 = null; assert !lst6.find() 它是正确的 - 没有错误发生
      猜你喜欢
      • 2011-04-24
      • 2016-06-20
      • 2017-05-28
      • 2017-05-07
      • 2018-08-09
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      相关资源
      最近更新 更多