Tuesday, May 25, 2010

Concise Groovy

The power of closures


Filter duplicates and write to csv file
def set = new HashSet();

new File("C:/temp/no2.csv").eachLine {
  line -> set.add(line)
}

new File("C:/temp/no3.csv").withWriter {writer, count = 0 ->
  set.each {
    element ->
    writer.append(element)
    count++
    if (count < set.size()) writer.append(",")
  }
}

No comments:

Post a Comment