Java Mailing List Archive

http://www.gg3721.com/

Home » user.groovy »

[groovy-user] list.collect with no nulls or null for lists?

Fred Janon

2008-08-02

Replies: Find Java Web Hosting

Author LoginPost Reply
I realized that I quite often write something like this:

blist = alist.collect { condition ? something : null}
and then I have to remove the nulls from blist.

def numdays = alldays.collect { it & opendays ? endays.get(it & opendays) : null }
println numdays // some nulls in the list
numdays - null

Basically I am looking for a way to build a list with collect but skipping the result if null, so I add a null to the list and I need to remove all the nulls after the collect. Is there a way to do that at the moment? Is there something in the future like a null entry for lists that would not be added to lists?

I checked the wish list but didn't see anything like that.

Thanks

Fred

Here is an example

def opendays = 1 + 4 + 8 + 32
def alldays = [1,2,4,8,16,32,64]
def endays = [1:'m',2:'tu',4:'w',8:'th',16:'f',32:'sa',64:'su']
//def frdays = [1:'lun',2:'mar',4:'mer',8:'jeu',16:'ven',32:'sam',64:'dim']

// Current way, annoying 'def strlist = []'
def strlist = []
alldays.each { def m = it & opendays ; if (m) strlist << endays.get(it & opendays) }
assert strlist ==  ["m", "w", "th", "sa"]
println strlist

// Collect way with annoying nulls
def numdays = alldays.collect { it & opendays ? endays.get(it & opendays) : null }
println numdays
numdays = numdays - null
assert numdays == ["m", "w", "th", "sa"]
println numdays

©2008 gg3721.com - Jax Systems, LLC, U.S.A.