嗨我收藏在我的控制器中,前言
def devices=[ [id:PPL000000011906, firstName:Adam, lastName:Baines], [id:PPL000000010836, firstName:Adam, lastName:Baines], [id:PPL000000015137, firstName:Adan, lastName:Saenz], [id:PPL000000015136, firstName:Adan, lastName:Saenz]]
我将从我的视角中获取id。如何根据ID从我的Map获取名字和姓氏值。
谢谢, 希瓦
答案 0 :(得分:2)
基本上,您可以使用find
找到具有给定id
的列表条目。这是一个例子
def devices = [ [id:'PPL000000011906', firstName:'Adam', lastName:'Baines'],
[id:'PPL000000010836', firstName:'Adam', lastName:'Baines'],
[id:'PPL000000015137', firstName:'Adan', lastName:'Saenz'],
[id:'PPL000000015136', firstName:'Adan', lastName:'Saenz'] ]
Closure<String> nameForId = { String id ->
devices.find { it.id == id }?.with { map ->
"$map.firstName $map.lastName"
}
}
assert nameForId( 'PPL000000015136' ) == 'Adan Saenz'
答案 1 :(得分:0)
我会这样做以获得一个字段:
devices.find { it.id == 'PPL000000011906' }?.firstName
如果你想要闭包和参数,我会这样做:
def findPerson = { person -> devices.find { it.id == person } }
def myPerson = findPerson('PPL000000011906')
println "FirstName: ${myPerson?.firstName} LastName: ${myPerson?.lastName}"
如果你想发疯,你可以这样做:
ArrayList.metaClass.findThingInMap = { field, value -> delegate.find { it[field] == value } }
这样做可以让你在包含哈希映射的任何数组列表中找到一个字段的值,这就是你所拥有的。
def myPerson = devices.findThingInMap('id', 'PPL000000011906')
println "FirstName: ${myPerson?.firstName} LastName: ${myPerson?.lastName}"
除非你需要灵活性,否则我不会这样做,但这显示了常规的真正力量和令人敬畏。