2
Ich habe eine Liste von Karten und ich möchte eine bestimmte Karte in der Liste abrufen und den Wert für einen bestimmten Schlüssel zurückgeben. Ich bin mir sicher, dass etwas Grundlegendes fehlt, aber ich kann das nicht schaffen. Ich habe mehrere fehlgeschlagene Versuche:Groovy: Suchen/geben Sie den Wert einer Karte nach Schlüssel in einer Liste der Karten zurück
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'
}
Gibt es einen sauberen Weg, um dies zu arbeiten?
Taste '==‚color'' - dies nichts tut. –
@OliverCharlesworth es tut im Zusammenhang mit einem 'find' Schließung –
@tim_yates - Nur als implizierte' return' - diese Schließung hat jedoch eine explizite 'return'. –