1

我有一张类似的地图。

     xxx-10.name ='welcome'
     xxx-10.age  ='12'
     xxx-10.std  ='2nd'

     xxx-12.name ='welcome'
     xxx-12.age  ='12'
     xxx-12.std  ='2nd'

     yyy-10.name ='welcome'
     yyy-10.age  ='12'
     yyy-10.std  ='2nd'

     yyy-12.name ='welcome'
     yyy-12.age  ='12'
     yyy-12.std  ='2nd'

wen 用户给 xxx 我必须返回包含所有 xxx 条目的子图,而不管与之关联的数字是多少。有没有办法使用正则表达式来实现这一点?或者没有迭代键?

SubMap 我可以使用该实用程序获得..

4

2 回答 2

5

groovy 中有一个用于集合的过滤器功能。见API

def result = [a:1, b:2, c:4, d:5].findAll { it.value % 2 == 0 }
assert result.every { it instanceof Map.Entry }
assert result*.key == ["b", "c"]
assert result*.value == [2, 4]

在您yourSearchString使用String.startsWith()搜索时:

map.findAll { it.key.startsWith(yourSearchString) }
于 2012-10-31T11:31:20.817 回答
3

这应该做你想要的。

def fileContents = '''xxx-10.name ='welcome'
                     |xxx-10.age  ='12'
                     |xxx-10.std  ='2nd'
                     |xxx-12.name ='welcome'
                     |xxx-12.age  ='12'
                     |xxx-12.std  ='2nd'
                     |yyy-10.name ='welcome'
                     |yyy-10.age  ='12'
                     |yyy-10.std  ='2nd'
                     |yyy-12.name ='welcome'
                     |yyy-12.age  ='12'
                     |yyy-12.std  ='2nd'''.stripMargin()

// Get a Reader for the String (this could be a File.withReader)
Map map = new StringReader( fileContents ).with {
  // Create a new Properties object
  new Properties().with { p ->
    // Load the properties from the reader
    load( it )
    // Then for each name, inject into a map
    propertyNames().collectEntries {
      // Strip quotes off the values
      [ (it): p[ it ][ 1..-2 ] ]
    }
  }
}

findByPrefix = { pref ->
  map.findAll { k, v ->
    k.startsWith( pref )
  }
}

findByPrefix( 'xxx' )

祈祷你不要删除这个问题;-)

于 2012-10-31T11:21:31.387 回答