R M
R M

Reputation: 165

Groovy Map in Map value retrieval

I am somewhat new to Groovy and am struggling with a Map of Maps issue.

Assuming I have a Groovy map defined as follows - each map entry consists of Brand, Weight and Charge:

// Each Map represents Brand, Weight, Charge

def crankcase = [
    ["GM", 22, 37],
    ["Ford", 221, 400],
    ["Dodge", 66, 150]
]

I am looking for the best way to be able to retrieve a given map entry based on Brand ( GM, Ford or Dodge ) and the associated Weight and Charge for that Brand.

I will be doing lookups constantly so I assume the solution she be performant.

Upvotes: 1

Views: 553

Answers (1)

cfrick
cfrick

Reputation: 37008

The data structure you are showing is not a map of maps - it is an vector of vectors (list of lists, array of arrays, ...). The difference is, that maps would have a key for each value before the value, separated with a :. E.g. [brand:GM, weight:22, charge:37] is a map.

You first would have to turn that into an vector of maps. E.g.

def crankcase = [
    ["GM", 22, 37],
    ["Ford", 221, 400],
    ["Dodge", 66, 150]
]

def map = crankcase.collect{ [["brand", "weight", "charge"], it].transpose().collectEntries() }

println map
// → [[brand:GM, weight:22, charge:37], 
//    [brand:Ford, weight:221, charge:400], 
//    [brand:Dodge, weight:66, charge:150]]

And then you could e.g. group that by brand, so you get a map of brands to vector of cases.

def casesByBrand = map.groupBy{ it.brand }

println casesByBrand

// → [GM:[[brand:GM, weight:22, charge:37]], 
//    Ford:[[brand:Ford, weight:221, charge:400]], 
//    Dodge:[[brand:Dodge, weight:66, charge:150]]]

Upvotes: 2

Related Questions