2013-11-27 85 views
-1

SSCCE:Groovy的grep和標工作

def map = [ 
    1 : "One" , 
    2 : "Two" , 
    3 : "Three" , 
    4 : "Four" , 
    5 : "Five" 
] 

def list = [1,2,3,4,5] 

// Using range in GREP 
assert list.grep(0..2) == [1,2] // why not [1,2,3] ?? Why exclude index = 2 from the range ? 
assert map.grep(0..2) == [] // why is this empty ?? 

// using subscript 
assert list[0..2] == [1,2,3] // It is [1,2,3]. As expected. Different from grep although same range 
assert map[0..2] == null // huh ? No values ? Why is this not [] ? 

我的問題是在SSCCE。我錯過了什麼?我的理解有什麼問題?

回答

1
  • list.grep(0..2)finds all instanceslist這是在[0, 1, 2]因此[1, 2]
  • 的唯一途徑,我可以得到map.grep返回任何東西是通過map.grep(LinkedHashMap.Entry)map.grep(map.entrySet()[ 0..2 ])
  • 上列出了getAt下標操作符如您預期
  • 0..2是一個有效的地圖密鑰即:[ (0..2):'tim' ],所以你不能以這種方式獲得一系列的條目