J  Calbreath
J Calbreath

Reputation: 2705

Scala: Read a text file and filter on list of values

I want to read in a text file and filter lines that contain only certain values in a particular column. So "if line 1, column 2 contains "Bob" or "Tom" or "Fred", then return that line. The result would only contain lines where the second element of each line is either Bob, Tom, or Fred.

It thought this would work:

 val trans = io.Source.fromFile(inputFile).getLines.map(x => x.split("\11")).filter(line =>("Bob", "Tom", "Fred").contains.line(2)).toArray

but after looking at it, it doesn't really make sense that it would work (and it doesn;t). I can do it with a single value like this:

val trans = io.Source.fromFile(inputFile).getLines.map(x => x.split("\11")).filter(line =>line(2) contains "Bob").toArray

but can't figure how do multiple values.

Any help is appreciated.

Upvotes: 2

Views: 2458

Answers (1)

0__
0__

Reputation: 67310

You want to check whether one column of a line—a single string—is contained in a sequence of strings:

val names = Seq("Bob", "Tom", "Fred")

Then your filter call becomes

...filter(line => names.contains(line(2)))

Upvotes: 3

Related Questions