Kshitiz Sharma
Kshitiz Sharma

Reputation: 18597

Understanding findAll in Groovy

Consider the following code:

String emptyString = '''

        '''
println "After trimming empty string has size: " + emptyString.trim().size()
println "Number of non empty elements in array: " + ([emptyString, 'kshitiz'].findAll({ it.trim() != 0}).size())

I expect the output to be 1. However the output is:

After trimming empty string has size: 0
Number of non empty elements in array: 2

I suspect that I may be missing something basic here but can't quite figure out what.

Upvotes: 2

Views: 8431

Answers (2)

Nathan Hughes
Nathan Hughes

Reputation: 96385

The expression in the closure {it.trim() != 0} returns true for both list entries regardless of if the string returned by it.trim() is empty or not, so findAll doesn't filter anything out and the size of the list returned by findAll is 2.

Fixes like {it.trim().length() != 0} or {it.trim() != ''} (which you can do in Groovy since == uses the equals method) will work but are not necessary. Groovy treats empty (zero-length) strings as false and non-empty strings as true, see these examples from groovy-lang.org:

assert 'a'
assert !''
def nonEmpty = 'a'
assert "$nonEmpty"
def empty = ''
assert !"$empty"

Removing the counterproductive != 0 gives

['', ' ', 'asdf'].findAll { it.trim() }.size()

which evaluates to 1, having successfully filtered out empty entries.

Upvotes: 2

Strelok
Strelok

Reputation: 51441

Your code should be:

 String emptyString = '''

    '''
 println "After trimming empty string has size: " + emptyString.trim().size()
 println "Number of non empty elements in array: " + ([emptyString, 'kshitiz'].findAll({ it.trim().length() != 0}).size())

Notice the use of the length() method. You were not comparing the length of the string.

Upvotes: 1

Related Questions