Reputation: 5199
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
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
Reputation: 21379
You can do as below:
JsonSlurper
find
to searchdef 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