Infinity: Easier Than You Think. Infinitely.

Spaghettified musings on software

  • January 2010
    S M T W T F S
    « Oct   May »
     12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31  

Feeling Groovy: Numbers List to Values List

Posted by gdjsky01 on 2010/01/30

So I have a bunch of strings being sent to me like 1,3,4,5,6

Those numbers are selections like foods I like. Maybe 1 means gnocchi, 3 means lasagna, 4 means creme brulee, etc. I needed to output these readable values not the numbers to a quick and dirty web page. Actually I need to output quite a few of them. Groovy to the rescue.

def map = [1:"apples", 2:"oranges",3:"grapes",4:"cherries"]
def text = "1,2"
def result = "apples, oranges"
assert result == text.split(',').collect {value -> map[value.toInteger()]}.join(", ")
// Thanks to Noah Sloan for an even groovier way!
assert result == map.subMap(text.split(',')*.toInteger()).values().join(", ")

text = "4"
assert "cherries" == text.split(',').collect {value -> map[value.toInteger()]}.join(", ")
// Thanks to Noah Sloan for an even groovier way!
assert "cherries" == map.subMap(text.split(',')*.toInteger()).values().join(", ")
text = ""
try {
assert "" == map.subMap(text.split(',')*.toInteger()).values().join(", ")
fail() // NumberFormatException - Validate your imputs - or use StringUtils
} catch(NumberFormatException nfex) {
}

Groovy is even smart enough to deal with a string of one value (no comma). You do have to be careful about that toInteger() call but then in real code you check your preconditions right?

Got a better way? Fast way? More Groovy-o-matic (idiomatic) way? Teach us all! Leave a comment.

Advertisements

5 Responses to “Feeling Groovy: Numbers List to Values List”

  1. noah said

    map.subMap(text.split(‘,’)*.toInteger()).values().join(“, “)

    is a little more Groovy 🙂

  2. Bob Brown said

    Here’s another way:

    http://wordpress.transentia.com.au/wordpress/2009/03/11/inventing-a-new-statement-for-groovy-in-10-minutes/

    • gdjsky01 said

      Thanks for the link. Very interesting tho I am always a bit leary of using exceptions for flow control! Best wishes. 🙂

  3. […] This post was mentioned on Twitter by groovyblogs.org, IT-Tanuki. IT-Tanuki said: RT @groovyblogs: Feeling Groovy: Numbers List to Values List — http://bit.ly/dhqQma — Going to Infinity Is Easier Than You Think […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: