Groovy GoodNess – Converting a List to String
The more I work on Groovy more I love it and groovy console is a charm to try out things even for Java. Checkout the code below and Imagine if you have do the same code in Java, how much lines of Code it will be.
//Converts a list say
//List myList = ["user", "pwd","address1", "address2"] to
//String resultStr = 'user','pwd','address1','address2'
//VERSION 1 of Code Written in Groovy but Inspired by Java
//Even thought the following Code is written in Groovy its, 100% of how problem would have been in Java
if(!myList.empty)
{
//takes out the square bracket from either sides
String resultStr=myList.substring(1, list_all_user_contacts.length()-1)
//Relaces the "double quotes with ","
resultStr=resultStr.replaceAll(",", "','")
//Appends apostoles ' at the start and end
resultStr="'"+resultStr+"'"
println resultStr
}
//Version2 : PURE Groovy, Checkout the Magic
String quote="'"
String resultStr="""$quote${myList.join("','")}$quote """
println resultStr
Comments
Post a Comment