我有一个地图列表,我想在列表中获取一个特定的地图,并返回给定键的值。 我确信我缺少一些基本的东西,但我无法做到这一点。我有几次尝试失败:
void "find map by key in a list of maps"() {
given: "a list of maps"
List favorites = [
[fruit: 'apple'],
[color: 'yellow'],
[activity: 'reading']]
when:
String favoriteColor = favorites.each {
it.find { key, value ->
key == 'color'
return value
}
}
// String favoriteColor = favorites.each { it['color'] }
// String favoriteColor = favorites.find { it.key == 'color' }
// String favoriteColor = favorites.collect { it['color'] }
// String favoriteColor = favorites*.get('color')
// String favoriteColor = favorites*.get('color').value
// String favoriteColor = favorites.collect { it['color'] }.value as String
// String favoriteColor = favorites.find { it['color'] }.value as String
then:
favoriteColor == 'yellow'
}
是否有一种干净的方法可以使这项工作?
答案 0 :(得分:4)
你可以简单地做
String favoriteColour = favorites.findResult { it.color }