开发者

Groovy Element comparison

Is this madness, or is this Sparta?

groovy:000> b = [1,2,3,4]
===> [1, 2, 3, 4]
groovy:000> b.count { !it.equals(4) }
===> 0
groovy:000> b.count { !it == 4 }     
===> 0
groovy:000> b.count { it == 4 } 
===> 0
groovy:000> b.count { it == 1 }
===> 0
groovy:000> b[0]
===> 1
groovy:000> b.each {开发者_JAVA技巧 println it }
1
2
3
4
===> [1, 2, 3, 4]
groovy:000> print b.class
class java.util.ArrayList===> null
groovy:000> b.each { println it.class }
class java.lang.Integer
class java.lang.Integer
class java.lang.Integer
class java.lang.Integer
===> [1, 2, 3, 4]
groovy:000> 4.equals(b[3])
===> true
groovy:000> 

I'm running into a case of "surprised expectations" here. Groovy tells me that I have an ArrayList of Integer, and I expect that I should be able to do cute little searches like the above 3 queries all tersely and sweetly. But no.

  1. What is the idiomatic Groovy way of doing the above (count the number of elements where x != some element)
  2. Why doesn't this work?


be aware that the method signature

public Number count(Closure closure)

is supported since Groovy 1.8.0 (current production is 1.7.10) - see http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#count(groovy.lang.Closure)

Before Groovy 1.8, the code above calls method 'count(Object value)', which counts the number of occurrences of the given value inside the collection. providing a closure instance as actual parameter 'value' leads to the results described above.


What is the idiomatic Groovy way of doing the above (count the number of elements where x != some element)

Here's one way:

def list = [3, 5, 3]

def countElementsNotEqualTo3 = list.findAll{ it != 3 }.size()
assert countElementsNotEqualTo3 == 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜