user_dev
user_dev

Reputation: 1431

How to find the key by comparing from value of a map in groovy?

I have a list which is having few urls. I am iterating over a map to find where the item from the list exists in the map. If value exists it should return the corresponding map key.

Here is the code:

def map= [:]
List<String> list = ["url1", "url2", "url3"]
for (project in activeJobs) {

    scm = project.scm;
    //println("${project.name}: " +
      //      "repositories: ${scm.repositories.collectMany{ it.getURIs() }}")
    def uriName = scm.repositories.collectMany{ it.getURIs() }
    uriName.eachWithIndex { item, index ->
        //println item
        uriName = uriName[index].toString().toLowerCase()
        map.put(project.name, uriName)
    }

}
list.each { url ->

    //println url
    //def item = map.find { value -> url }
    //println item
    //println url
    print map.find { it.value == url }?.key

}

Last print statement always returns null.

Upvotes: 0

Views: 669

Answers (3)

user_dev
user_dev

Reputation: 1431

uriName = uriName[index].toString().toLowerCase()

Is the problem here

Upvotes: 0

dmahapatro
dmahapatro

Reputation: 50245

Using findResults on Map:

List<String> list = ["url1", "url2", "url3"]
Map<String, String> map = [a: "url1", b: "url2", c: "url5", d: "url3"]

assert map.findResults { k, v -> v in list ? k : null } == ['a', 'b', 'd']

Upvotes: 1

saml
saml

Reputation: 794

I just ran the following JUnit Test:

@Test
void testit(){
  def map = ["k1" : "url1", "k2" : "url2", "k3" : "url3"]
  def list = ["url1", "url2", "url3"]
  list.each { url ->
  print map.find { it.value == url }?.key

  }
}

And the output was:

k1k2k3

Could you post more of your code if it still doesn't work, but I don't think your problem is here.

Sam

Upvotes: 0

Related Questions