0

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.

Community
  • 1
  • 1
Sohaib
  • 4,556
  • 8
  • 40
  • 68
  • 4
    My solution would be simple: `Seq(a,b,c,d).filter(_ != null).toSet` (or, for example, `Seq(a,b,c,d).map(Option.apply).flatten.toSet` if you want to use options) – Patryk Ćwiek Jun 24 '15 at 09:31
  • @PatrykĆwiek I like it. Can we change that map and flatten to flatMap? I guess no cause in that case we flatten first and then map here we are mapping first and then flattening. Am I right? – Sohaib Jun 24 '15 at 09:38
  • @PatrykĆwiek How about this if we are using options: `Seq (a, b, c, d).filter(_.isDefined).map(_.get).toSet` – Sohaib Jun 24 '15 at 09:46
  • 1
    @Sohaib That should also work, although using `.get` on `Option` usually looks suspicious (and sometimes is a warning/error using different linters, depending on settings). If you're starting with a `Seq[Option[DateTime]]`, then just `seq.flatten.toSet` should do the trick. – Patryk Ćwiek Jun 24 '15 at 09:53
  • Instead of filter and and flatten You can also use : Seq(Option(1),Option(2),None,None,Option(5)).collect{case x : Option[Int] if x.nonEmpty => x.get} – curious Jun 24 '15 at 10:33
  • @PatrykĆwiek Thanks. You can post that as an answer and Id mark it correct. – Sohaib Jun 24 '15 at 10:35

2 Answers2

1

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.

Rüdiger Klaehn
  • 12,445
  • 3
  • 41
  • 57
1

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
Patryk Ćwiek
  • 14,078
  • 3
  • 55
  • 76