Kajal
Kajal

Reputation: 739

Findall with array of string groovy

I have a string /sample/data. When I split using split I get the following result,

["","sample","data"]

I want to ignore the empty string(s). So I tried the following code,

"/sample/data".split('/').findAll(it != "")

It gives me an error "cannot call String[] findAll with argument bool".

How can I split and get a List without empty string in it?

Upvotes: 2

Views: 1087

Answers (3)

cfrick
cfrick

Reputation: 37008

Parens would work (see comments on question). So your solution is already close:

"/a/b".split("/").findAll()

Because most of the Groovy functions have a zero arity, which will call the function with an identity closure. And since an empty string is considered falsey, this will filter them out.

Upvotes: 1

Evgeny Smirnov
Evgeny Smirnov

Reputation: 3016

split method returns array. If you need List, use tokenize

"/sample/data".tokenize('/')

also you don't need to use findAll in this case.

Upvotes: 3

Rao
Rao

Reputation: 21359

You can do as below:

println "/sample/data".split('/').findAll {it}

findAll {it} would fetch all the non empty values.

Upvotes: 1

Related Questions