i have following use case, in iterating multiple times on same collection, , every time find different item in collection.
class foo(policytodata: map[string, myclass]){ val milk: option[myclass] = policytodata.values.find(_.`type` == milk) val meat: option[myclass] = policytodata.values.find(_.`type` == meat) val bread: option[myclass] = policytodata.values.find(_.`type` == bread) val other: list[myclass] = policytodata.values.filter(_.`type` == other).tolist }
is there better way it? 1 iteration?
if it's large collection, folding map means build collection of interest.
scala> case class c(name: string) defined class c scala> val cs = list(c("milk"),c("eggs"),c("meat")) cs: list[c] = list(c(milk), c(eggs), c(meat)) scala> cs.foldleft(map.empty[string,c]) { | case (m, c @ c("milk" | "meat")) if !m.contains(c.name) => m + (c.name -> c) | case (m, _) => m } res5: scala.collection.immutable.map[string,c] = map(milk -> c(milk), meat -> c(meat))
then
scala> val milk = res5("milk") milk: c = c(milk) scala> val bread = res5.get("bread") bread: option[c] = none
the original groupby
solution deleted because commented work, in fact it's straightforward expression, if creating intermediate map of lists ok.
scala> cs.groupby(_.name) res0: scala.collection.immutable.map[string,list[c]] = map(meat -> list(c(meat)), eggs -> list(c(eggs)), milk -> list(c(milk))) scala> res0.get("milk").map(_.head) res1: option[c] = some(c(milk)) scala> res0.get("bread").map(_.head) res2: option[c] = none
or
scala> cs.filter { case c("milk" | "meat") => true case _ => false }.groupby(_.name) res4: scala.collection.immutable.map[string,list[c]] = map(meat -> list(c(meat)), milk -> list(c(milk)))
Comments
Post a Comment