Skip to content

Instantly share code, notes, and snippets.

@Teqqles
Last active February 27, 2018 07:21
Show Gist options
  • Save Teqqles/43cf8c359f45cde982a5 to your computer and use it in GitHub Desktop.
Save Teqqles/43cf8c359f45cde982a5 to your computer and use it in GitHub Desktop.
Filter CSV by Field Heading using Scala
case class CsvWithHeadersExtractor( text: List[ String ] ) {
val head = removeQuotations( text.map( x => x.split( "," ).toList ).head )
val list = for {
tail <- text.map( x => x.split( "," ).toList ).tail
} yield {
head zip removeQuotations( tail )
}
def filterByField( columnName: String ): List[ String ] = {
list.flatMap( _.filter( x => x._1 == columnName ).map( _._2 ) )
}
private def removeQuotations( fields: List[ String ] ): List[ String ] = {
fields.map( _.replaceAll( "^\"|\"$", "" ) )
}
}
val sourceList = CsvWithHeadersExtractor( List( "id,name", "1,David", "2,Patrick" ) )
//sourceList: CsvWithHeadersExtractor = CsvWithHeadersExtractor(List(id,name, 1,David, 2,Patrick))
sourceList.filterByField( "name" )
//res0: List[String] = List(David, Patrick)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment