Friday, 3 November 2017

collectFirst on Map of Sequence


To find a product first bought from a map of year to List of Items

scala> def firstGuitar(list: Seq[String]) = list.collectFirst { case item if item == "Guitar" => item }
firstGuitar: (list: Seq[String])Option[String]

scala> Map(2016 -> Seq("Cap", "Guitar", "Cap"), 
           2017 -> Seq("Here and now album", "Drum Kits", "Cap", "Guitar")).collectFirst { case (year, itemsBought) 
                        if firstGuitar(itemsBought).nonEmpty => (year -> firstGuitar(itemsBought))}
res2: Option[(Int, Option[String])] = Some((2016,Some(Guitar)))

scala> Map(2016 -> Seq("Cap", "Camera", "Cap"), 
            2017 -> Seq("Here and now album", "Drum Kits", "Cap", "Tshirt")).collectFirst { case (year, itemsBought) 
                       if firstGuitar(itemsBought).nonEmpty => (year -> firstGuitar(itemsBought))}
res3: Option[(Int, Option[String])] = None


No comments:

Post a Comment