IAmYourFaja
IAmYourFaja

Reputation: 56934

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.

Upvotes: 42

Views: 57642

Answers (4)

mih0vil
mih0vil

Reputation: 158

As I see it in documentation, join is deprecated In Collections, but not in Iterable.

def joinedValues = (values as Iterable).join ', '

Using closures you could try to write it with .inject, head and tail:

values.head() + (values.size() > 1 ? values.tail().inject( '' ) { acc, i -> acc+', ' + i } : '')

Upvotes: 3

Durandal
Durandal

Reputation: 5663

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(",")

Upvotes: 49

kousen
kousen

Reputation: 3167

If you're worried about the deprecation issue, the current version of the Groovy JDK (http://groovy-lang.org/gdk.html) shows a join(String) method in Iterable, Object[], and Iterator, none of which are deprecated.

Since all the collections implement Iterable, your original syntax was fine.

If you really want to use a closure, then

List strings = ['this', 'is', 'a', 'list']
String result = strings.inject { acc, val ->
    "$acc,$val"
}
assert result == 'this,is,a,list'

works, but it's certainly not any simpler than just strings.join(',').

Upvotes: 6

dmahapatro
dmahapatro

Reputation: 50265

You need to use the Iterable or Iterator<Object> version of join:

join(Iterator<Object> self, String separator)

instead of

join(Collection self, String separator).

This is the only variety of join which is deprecated.

join(Iterable self, String separator) and join(Object[] self, String separator) are few more which are in use.

Upvotes: 4

Related Questions