thisisnotabus
thisisnotabus

Reputation: 2069

Groovy remove space indexes from array

headers is an array that is populated from a file. When I print headers, I get:

headers = ["The Year", , , "The Make", "The Model"]

I'm trying to use headers.remove(' ') to get rid of those two cells that are just spaces. It will not run or compile with that syntax, and I cannot find what I am doing wrong. I have tested:

def list1 = ['j', 2, 3, 4]

list1.remove('j')

And it works just fine. I cannot figure out what I'm doing wrong.

Upvotes: 0

Views: 563

Answers (1)

doelleri
doelleri

Reputation: 19682

Assuming that ["The Year", , , "The Make", "The Model"] is actually the toString representation of the list

groovy:000> ["The Year", , , "The Make", "The Model"]
ERROR org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed:
groovysh_parse: 1: unexpected token: , @ line 1, column 14.
   ["The Year", , , "The Make", "The Model"]
            ^
groovy:000> ['"The Year"', '', '', '"The Make"', '"The Model"']
===> ["The Year", , , "The Make", "The Model"]

I think headers.remove(' ') isn't working because the elements aren't actually spaces, they're empty. I'm not sure why headers.remove('') wouldn't work, except that you'd need to use headers.removeAll('').

A better option would be to use something like headers.findAll { it.trim() != '' }.

Upvotes: 2

Related Questions