Creating immutable Hashsets in scala conditionally

87 Views Asked by At

I have a small function which does this

val s = MutableHashSet[DateTime]()
if (a != null) s.add(a)
if (b != null) s.add(b)
if (c != null) s.add(c)
if (d != null) s.add(d)
s

I know using null is bad (and I can use option) but let us forget that for now and concentrate more upon how to make this HashSet immutable. MutableHashSet is the same as scala.collection.mutable.HashSet. I saw a similar question here. However creating multiple Seq and then a hashset from it looks like too much of an overkill.

2

There are 2 best solutions below

0
On BEST ANSWER

Per request, I'm moving my comment to an answer.

The easiest and most straightforward option would be:

Seq(a,b,c,d).filter(_ != null).toSet

Alternatively, you can convert elements to Option[DateTime] first:

val seq = Seq(a,b,c,d).map(Option.apply)

and then, once you have a Seq[Option[DateTime]] you can do:

seq.flatten.toSet
0
On

If you have a small and fixed number of values that you want to convert to a set, I would just use

Set.empty[DateTime] ++ Option(a) ++ Option(b) ++ Option(c) ++ Option(c)

If you have a large or variable number of values, the solution from Patryk seems the best.