Reputation: 1948
Is there an easy syntax or convenience method (without looping by myself) for checking to see if a value exists in a Map
which is in a List
? For example what I am trying to do is:
def myList = []
myList.push([first: "John", last: "Doe"])
println myList.contains(it -> it.first == "John")
should print true but syntax is incorrect. Basically, I need to know if the list contains a map such that in that map the value of the "first" key is "John".
Upvotes: 2
Views: 1659
Reputation: 50245
Another simpler check could be using spread operator as below
assert 'John' in myList*.first
UPDATE
Benchmarking the performance between usage of find
and in
provides result that incline towards usage of in
if list size is small.
Refer and run this GIST. Results may vary, but it is surprising that in
consumes less CPU consistently against find
when the list size is small (as shown in question, refer first result). Below is the set of results recorded as I write this update.
user system cpu real
findTestWithSmallerListSize 571 0 571 598
inListTestWithSmallerListSize 411 0 411 411
findTestWithMatchPresentInEnd 2714872 43 2714915 2739768
inListTestWithMatchPresentInEnd 2266303 39 2266342 2431595
findTestWithMatchPresentInAverageCenter 2141836 39 2141875 2263714
inListTestWithMatchPresentInAverageCenter 2261387 37 2261424 2438485
findTestWithMatchPresentInFirst 1667364 27 1667391 1813254
inListTestWithMatchPresentInFirst 2288471 37 2288508 2425089
Based on the above result I agree that if the match is present in the beginning or towards the beginning of the list (4th result from above) then find
is fully efficient.
Upvotes: 4
Reputation: 24776
Using find may be a better solution:
def myList = []
myList.push([first: "John", last: "Doe"])
def exists = (myList.find{ it -> it.first == 'John'} ? true : false)
assert exists == true
exists = (myList.find{ it -> it.first == 'Jane'} ? true : false)
assert exists == false
Upvotes: 3