Rodrigo_V
Rodrigo_V

Reputation: 180

Check if element wise condition in Scala list

I would like to get a list such as

val mask = List(true, false, false, false, false)

when evaluating elementwise if an element is equal to "DoubleType"

val column_type = List("DoubleType", "LongType", "LongType", "LongType", "StringType")

I got something similar when using

val mask = new ListBuffer[String]()

for (name <- column_type)
    mask += (name == "DoubleType").toString

But you can see that I had to turn every element into a string, otherwise I get an error. And this way I can't use it later as a mask. What should I do? Any more scalastic way of solving this issue?

Upvotes: 0

Views: 996

Answers (3)

Charlie Flowers
Charlie Flowers

Reputation: 1380

The most concise way to accomplish your goal is via map:

scala> val mask = column_type.map(_ == "DoubleType")
mask: List[Boolean] = List(true, false, false, false, false)

Scala has a rich suite of tools for operating on collections, see https://docs.scala-lang.org/overviews/scala-book/collections-methods.html for more details.

Upvotes: 0

md samual
md samual

Reputation: 325

val mask=column_type.map(a=>a.equals("DoubleType"))

Upvotes: 0

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27535

You can use .map with a predicate

val mask = column_type.map(_ == "DoubleType")

Upvotes: 4

Related Questions