A friend was telling me about a question he saw on an exam and wanted to know my thoughts on it. The exam wanted you to write out the function in pseudo code first and then write it in Java and ColdFusion. The question was pretty basic but it was a good one to think about. Write a method that will accept a sentence as an argument. The method will take this string and reverse the order of the words in the argument.
So following our instructions the first thing we need to do is talk out our thought process for this method.
- create a variable to hold our new string
- Split the argument into words using a space as the delimiter
- loop over out list of words
- take the current word in the loop and prepend it to our new string
That was pretty easy and gives us some really straight forward instructions on how to create our method. First I will write the method in Java. Lucky for us Java has a wonderful class called StringTokenizer. This class will allow us to break our string into tokens and has convenience methods for looping over the tokens and getting the next token.
As you might know ColdFusion can leverage any Java class. Because of that our method in ColdFusion should look pretty much the same. If your not familiar with ColdFusion the init method is just a way for us to pass something into the Java constructor.

#1 by Tony Nelson on 6/29/10 - 8:59 AM
public string function reverseWords(required string str) {
str = listToArray(str, " ");
createObject("java", "java.util.Collections").reverse(str);
return arrayToList(str, " ");
}
#2 by Tony Miller on 6/29/10 - 10:02 AM
<cfloop from="#ListLen(sentence, ' ')#" to="1" step="-1" index="x">
<cfoutput>#ListGetAt(sentence, x, ' ')#</cfoutput>
</cfloop>
Your solution is no doubt much faster, though.
#3 by Dan Vega on 6/29/10 - 10:26 AM
@Tony N - I didn't even think about that one, nice catch!
#4 by Mark Mandel on 6/29/10 - 5:04 PM
var builder = createObject("java", "java.lang.StringBuilder").init(str);
return builder.reverse().toString();
Howzat for simple? ;)
#5 by Jamie Krug on 7/1/10 - 11:44 AM
var result = listToArray( str, ' ' );
createObject( 'java', 'java.util.Collections' ).reverse( result );
return result;
#6 by Jamie Krug on 7/1/10 - 1:45 PM
return arrayToList( result, ' ' );
#7 by Jamie Krug on 7/1/10 - 1:51 PM
#8 by Mark Mandel on 7/1/10 - 6:34 PM
Your solution is definitely the best one for simplicity for sure.