Last active
February 27, 2018 07:21
-
-
Save Teqqles/43cf8c359f45cde982a5 to your computer and use it in GitHub Desktop.
Filter CSV by Field Heading using Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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