Crankrune Crankrune - 1 year ago 91
Groovy Question

Groovy: Use range as key in map?

I'm still kinda new to Groovy, just used it in a program called FileBot. Anyway, to sort some things well, without writing 10,000 lines of code, I want to be able use a range as the key in a map. So basically what I want to do is if 'a' is between '1' and '10' return 'x' value. I know I could write it out as

{a >= 1 && <=10 ? 'Do This' : null}
but that would be a lot more writing to do that. Also, I obviously want to use this for multiple different ranges, or this wouldn't be an issue.

Similarly, if there is any easier way to do this, I thought maybe with a csv file, but I'm not sure how exactly.

Any help is much appreciated!

Answer Source

Approach 1: As You asked

You can create the map with ranges pretty easily

Assuming you have map like below with ranges as key

Map sampleMap = [:]

sampleMap << [(1..10): "In one ten", (20..30): "In twenty thirty"]

Then you can easily find if your element is present in your map range or not like below

def found = sampleMap.find { entry -> entry.key.contains(2) }
println "found : " + found.value

output :

found : In one ten

Approach 2 :

Well you can also take advantage of the groovy switch case like below

def age = 5

    case 1..10 : 
        //do your work
        println "In one ten"

    case 21..50 : 
        //do your work
        println "In twenty fifty"

    case 51..65 :    
        //do your work
        println "In fifty sixty"

        //if nothing matches do something here

Output :

In one ten
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download