Home > database >  recursive search of a value in a map
recursive search of a value in a map

Time:03-09

I am trying to do the following: I have a nested map (maps within a map) and I want to find out if a selected value (e.g. null) occurs in any of these maps. If this value does occur in any of the maps, I want the function to return a true statement. Considering this, I thought that a recursive function would do the trick:

public boolean search(def root) {
    found = false
    root.each{ def it ->
        if (it.value instanceof Map) {
            found = search(it.value)
        } else if (it.value == null) {
            println "value found"
            found = true
        }
    }
    return found
}

Now when testing this with a map, I do not get the correct result even though my output indicates that my function is doing the correct iteration. Can anyone help me why this happens. Thanks a lot in advance!

Edit: Here is an example map where I don't get the expected result. Even though there is a value that is null, the search function returns a false statement:

def map = [name: [name: [name:  
               [test: [selection : [pet : null]]],
           age: 42, city: "New York"], 
           age: 42, city: [name: [name: [test:"New York"]]]], 
           age: 42, city: "New York"]

CodePudding user response:

public boolean search(def root) {
    return root.find{
        if (it.value instanceof Map) {
            return search(it.value)
        } else if (it.value == null) {
            return true
        }
        return false
    }
}
  • Related