Aaron
Aaron

Reputation: 686

Remove empty tuples from Seq[(String,Any)] in Scala

Suppose I have Seq[(String, Any)]

(Foo,1 ) 
(bar,2)
(baz,)

and I want to filter out baz as it does not have a value how can I check and remove (baz,) only

Upvotes: 0

Views: 944

Answers (2)

Andrey Tyukin
Andrey Tyukin

Reputation: 44908

Something like this maybe?

seq.filterNot { case (_, y) => (
    y.isInstanceOf[String] && 
    y.asInstanceOf[String].forall(_.isWhitespace)
  ) || y == null
}

After testing my own and @BrianMcCutchon's intermediate solution proposals in a little micro-benchmark, I came to the conclusion that

seq.filterNot { 
  case (_, s: String) => s.forall(_.isWhitespace)
  case (_, n) => n == null
}

is both one of the shortest, and also one of the fastest solutions. This is essentially @BrianMcCutchon's pattern matching combined with isWhitespace, and transformed through De-Morgan's Laws (avoids inner negation around isWhitespace, but works with forall and filterNot instead).

That's kind-of a merge between the two answers, I'm not sure how to deal with that? Should I move it into a separate community wiki answer? (upvoted the other answer for now, to rebalance a little bit)

Upvotes: 1

Brian McCutchon
Brian McCutchon

Reputation: 8584

To remove tuples whose second part contains null or a whitespace-only string:

someList.filter {
  case (_, s: String) => s.trim.nonEmpty
  case (_, x) => x != null
}

I think this is pretty readable, but, if performance is an issue, you might replace s.trim.nonEmpty with s.exists(!Character.isWhitespace(_)).

Upvotes: 3

Related Questions