How to elegantly combine the [List] option into a list?

I tried unsuccessfully to write these 3 codes:

aList.foldLeft(List()){(accu, element) => map.get(elment):::accu} aList.foldLeft(List()){(accu, element) => if (!map.get(element).isEmpty) map.get(element):::accu} aList.foldLeft(List()){(accu, element) => map.get(elment).exists(_:::accu)} 

Does anyone know how to do this to combine an option into a list?

+6
source share
4 answers

To combine an option with a list, you can simply do option.toList ++ list

To combine Option[List[A]] with List[A] optionOfList.toList.flatten ++ list

The basic idea is that you can always convert an option to a list of 0 or one item, which makes it easy to combine them with lists in different ways.

+25
source

Sprinkle some scalaz :

 import scalaz._; import Scalaz._ 

And setting:

 scala> val optList = some(List(1, 2, 3, 4) optList: Option[List[Int]] = Some(List(1, 2, 3, 4)) scala> val list = List(5, 6, 7) list: List[Int] = List(5, 6, 7) 

Then I can do:

 scala> ~optList ::: list res0: List[Int] = List(1, 2, 3, 4, 5, 6, 7) 

Basically ~ is a unary method bound to Option[A] , where for type A there is zero. Null for the list of course Nil

+1
source

if you want to add an option to the end of the list just use List.++

 val ss = Seq(1,2) // ss: Seq[Int] = List(1, 2) ss ++ Option(3) // res0: Seq[Int] = List(1, 2, 3) 
+1
source

The answers of @oxbow_lakes and @rjsvaljean are very good, but they still miss one possible case that could be resolved by the very idiomatic Scala:

 scala> List(1,2,3) res6: List[Int] = List(1, 2, 3) scala> Option(List(5,6,7)) res7: Option[List[Int]] = Some(List(5, 6, 7)) scala> for (l<-res7) yield l ++ res6 res8: Option[List[Int]] = Some(List(5, 6, 7, 1, 2, 3)) scala> for(l<-(None:Option[List[Int]])) yield l ++ res6 res9: Option[List[Int]] = None 

The missing case shown by the above code should None yield None instead of Nil ?

0
source

Source: https://habr.com/ru/post/1439509/


All Articles