Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grooviest way to join collection of Strings in Groovy 2.x

I just tried:

List<String> values = getSomehow() values.join(",") 

But see that join has been deprecated as of 2.1. So I ask: How should I be writing this in accordance with the latest preferred/non-deprecated syntax?

Also, is there a way to accomplish this with closures? I feel like I could be utilizing collect() or something similar here.

like image 509
IAmYourFaja Avatar asked Nov 22 '14 02:11

IAmYourFaja


People also ask

How do I join two strings in Groovy?

Groovy - Concatenation of Strings The concatenation of strings can be done by the simple '+' operator. Parameters − The parameters will be 2 strings as the left and right operand for the + operator.

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

How do you join a string?

Note: The join() method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.


1 Answers

You can use the Iterator variation of the join method in DefaultGroovyMethods. It's signature is the same, only the separator needs to be passed in.

It would look like this:

List<String> values = ["string1", "string2", "string3"] String joinedValues = values.join(",") 

Or you can do it all on one line:

String joinedValues = ["string1", "string2", "string3"].join(",") 
like image 104
Durandal Avatar answered Sep 21 '22 22:09

Durandal