簡體   English   中英

在每個閉包中檢查地圖時出現Groovy問題

[英]Groovy issue when checking maps in each closure

我有需要檢測是否有一個實用方法Map<String,Integer>包含條目(鍵)其值為零(0):

def mapIsAllZeros(Map<String,Integer> toCheck) {
    println toCheck
    toCheck.each {
        if(it.value != 0) {
            return false
        } else {
            println "Value is : " + it.value
        }
    }

    println "Returning true..."
    true
}

因此:

Map<String,Integer> m1 = new HashMap<String,Integer>()
m1.put("fizz", 0)
m1.put("buzz", 0)

Map<String,Integer> m2 = new HashMap<String,Integer>()
m2.put("fizz", 0)
m2.put("buzz", 1)

boolean m1Check = mapIsAllZeros(m1) // TRUE
boolean m2Check = mapIsAllZeros(m2) // FALSE

但是,當我運行此方法通過m2我得到:

[fizz:0, buzz:1]
Value is : 0
Value is : 0
Returning true...

這是怎么回事?

each不能返回。 使用find代替。 也可以一行完成: [fizz:0, buzz:1].every{!it.value}

def mapIsAllZeros(Map<String,Integer> toCheck) {
    return toCheck.values().every{it==0}
}
assert !mapIsAllZeros([fizz: 0, buzz: 1])
assert !mapIsAllZeros([fizz: 1, buzz: 1])
assert mapIsAllZeros([fizz: 0, buzz: 0])
assert !mapIsAllZeros([fizz: null, buzz: null])

編輯:感謝@dmahapatro:由於方法名稱建議對零進行正確檢查,因此我們不使用groovy-truth,因此null :s不會導致誤導

這里的問題是return語句是從each閉包而不是mapIsAllZeros方法返回的。 即閉包返回false,然后each繼續迭代。

因此,您應該使用除each以外的其他東西。 例如,使用find

boolean mapIsAllZeros(Map<String, Integer> toCheck) {
    !(toCheck.find { it.value != 0 })
}

另一種選擇是使用for循環:

boolean mapIsAllZeros(Map<String, Integer> toCheck) {
    for (entry in toCheck.entrySet()) {
        if (entry.value != 0) 
           return false
    }
    return true
}

each閉包返回的問題已得到很好的闡明,不過,您也可以使用以下代碼(從@Steinar借用的方法名)

boolean mapIsAllZeros(Map<String, Integer> toCheck) {
   !toCheck.values().contains(0)
}

簡單並使用眾所周知的API。

比較唯一值的解決方案:

def mapIsAllZeros(map) {
  map*.value.unique() == [0]
}

assert !mapIsAllZeros([fizz: 0, buzz: 1])
assert !mapIsAllZeros([fizz: 1, buzz: 1])
assert mapIsAllZeros([fizz: 0, buzz: 0])

因為這里沒有足夠的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM