2016-03-20 11 views
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?

+1

Taste '==‚color'' - dies nichts tut. –

+0

@OliverCharlesworth es tut im Zusammenhang mit einem 'find' Schließung –

+0

@tim_yates - Nur als implizierte' return' - diese Schließung hat jedoch eine explizite 'return'. –

Antwort

3

können Sie tun einfach

String favoriteColour = favorites.findResult { it.color } 
Verwandte Themen