Richie
Richie

Reputation: 5199

How to use find to search list of hashmaps

In groovy I have a list of hash maps.

If I want to search / get a record within this map for one combination of subtype and domain how can i do it? P.s. There will likely be more attributes in the maps but I haven't included them here for simplicity .

[{
    "subtype__c": "SUBTYPE_ONE",
    "domain__c": "DOMAIN_ONE"
}, {
    "subtype__c": "SUBTYPE_TWO",
    "domain__c": "DOMAIN_TWO"
}, {
    "subtype__c": "SUBTYPE_THREE",
    "domain__c": "DOMAIN_THREE"
}, {
    "subtype__c": "SUBTYPE_FOUR",
    "domain__c": "DOMAIN_FOUR"
}]

Upvotes: 1

Views: 40

Answers (2)

Abbas Gadhia
Abbas Gadhia

Reputation: 15100

You can try the following code.

List<Map<String, String>> list = [
    ["subtype": "s1", "domain": "d1"],
    ["subtype": "s2", "domain": "d2"],
]
list.find({ Map<String, String> map -> map["subtype"] == "s1" && map["domain"] == "d1"})

If there is a possibility of finding multiple such maps, then use "findAll" instead.

List<Map<String, String>> found = list.findAll({ Map<String, String> map -> map["subtype"] == "s1" && map["domain"] == "d1"})

Upvotes: 0

Rao
Rao

Reputation: 21379

You can do as below:

  • Define a map with search crieteria
  • Parse the data with JsonSlurper
  • Use find to search
def filterCriteria = [subtype__c: 'SUBTYPE_ONE', domain__c: 'DOMAIN_ONE']

def jsonString = """[{
    "subtype__c": "SUBTYPE_ONE",
    "domain__c": "DOMAIN_ONE"
}, {
    "subtype__c": "SUBTYPE_TWO",
    "domain__c": "DOMAIN_TWO"
}, {
    "subtype__c": "SUBTYPE_THREE",
    "domain__c": "DOMAIN_THREE"
}, {
    "subtype__c": "SUBTYPE_FOUR",
    "domain__c": "DOMAIN_FOUR"
}]"""

def json = new groovy.json.JsonSlurper().parseText(jsonString)

println json.find{it == filterCriteria}

You can quickly try the same online demo

Upvotes: 2

Related Questions