Combining two Option[List[String]] in Scala

scala merge two lists without duplicates
scala combine two lists
scala join two lists by key
scala concatenate list of lists
scala zip two lists
scala add element to list
scala merge two maps
scala combine two iterables

I have two Options

val opt1 = Some(List("Sal", "Salil"))
val opt2 = Some(List("Sal2", "Salil2"))

Either opt1 or opt2 could be None. If either one is None then I want an option with the List contained in the other. If both are None then None should be returned.

If both are Some then a Some with a list containing elements from both lists as shown below:

Some(List(Sal, Salil, Sal2, Salil2))

I know I can do this by hand, but is there an elegant way to do this? For-comprehensions don't work if one of the Options is a None.

Option((opt1 ++ opt2).flatten.toList).filter(_.nonEmpty)

How to merge (concatenate) Lists in Scala, First, you can merge two Scala lists using the ::: method of the List class, as demonstrated here at the Scala command prompt: scala> val a  There are at least three ways to merge/concatenate Scala List instances, as shown in the examples below. 1) The Scala List ::: method. First, you can merge two Scala lists using the ::: method of the List class, as demonstrated here at the Scala command prompt:

You can do this nicely using semigroup appending with scalaz or cats:

import scalaz._, Scalaz._ // for cats use `import cats._, implicits._`

val opt1 = Option(List("Sal", "Salil"))
val opt2 = Option(List("Sal2", "Salil2"))

scala> opt1 |+| opt2
res0: Option[List[String]] = Some(List(Sal, Salil, Sal2, Salil2))

scala> opt1 |+| None
res1: Option[List[String]] = Some(List(Sal, Salil))

scala> Option.empty[List[String]] |+| None
res2: Option[List[String]] = None

Otherwise, with the standard library you may need to handle it case-by-case:

(opt1, opt2) match {
    case (Some(a), Some(b)) => Option(a ++ b)
    case (Some(a), None) => Option(a)
    case (None, Some(b)) => Option(b)
    case _ => None
}

Or use collection methods to flatten them down:

scala> List(opt1, opt2).flatten.flatten
res5: List[String] = List(Sal, Salil, Sal2, Salil2)

scala> List(opt1, None).flatten.flatten
res6: List[String] = List(Sal, Salil)

How to merge Scala Lists, Just started using scala for spark, and I have the following function in which I want to def merge(): Option[Seq[(String, String)]] = val seq1: Option[Seq[(String, (seq1, seq2) match { case (Some(one), Some(two)) => Some(one ++ two) case It all works because Semigroup[Option[A]] combines options just like you want it  zip — Combine two optional values to make a paired optional value; unzip — Split an optional pair to two optional values; unzip3 — Split an optional triple to three optional values; toList — Unary list of optional value, otherwise the empty list; A less-idiomatic way to use scala.Option values is via pattern matching:

I don't think there is only one, proper, elegant way to achieve that. There is my proposition:

val opt1 = Some(List("Sal", "Salil"))
val opt2 = Some(List("Sal2", "Salil2"))

def merge(xs: Option[Iterable[_]]*) = xs.flatten.reduceLeftOption(_ ++ _)

With the results:

merge (opt1, opt2)
res1: Option[Iterable[_]] = Some(List(Sal, Salil, Sal2, Salil2))

merge (None, opt2)
res2: Option[Iterable[_]] = Some(List(Sal2, Salil2))

merge (opt1, None)
res5: Option[Iterable[_]] = Some(List(Sal, Salil))

merge (None, None)
res6: Option[Iterable[_]] = None

How to concat 2 Option[Seq[(String, String)]] elegantly : scala, val name: Option[String] = request getParameter "name" val upper = name map { _.trim } filter { _.length != false if empty; zip — Combine two optional values to make a paired optional value optional values; toList — Unary list of optional value, otherwise the empty list def flatten[B](implicit ev: <:<[A, Option[B]]): Option[B]. Scala Lists are quite similar to arrays which means, all the elements of a list have the same type but there are two important differences. First, lists are immutable, which means elements of a list cannot be changed by assignment.

No flatten required.

opt1.fold(opt2)(lst => Some(lst ++ opt2.getOrElse(Nil)))

Scala Standard Library 2.13.3, val name: Option[String] = request getParameter "name" val upper = name map asInstanceOf[List[String]] will not. Partitions this iterable collection in two iterable collections according to a [use case] Returns a option formed from this option and another iterable collection by combining corresponding elements in pairs. This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.22, “How to Merge Scala Sequential Collections” Problem. You want to join two Scala sequences into one sequence, either keeping all of the original elements, finding the elements that are common to both collections, or finding the difference between the two sequences.

Another way using for and yield:

val xs = Some(List(1,2,3))
val ys = Some(List(4,5,6))
val xys = for {
  x <-  if(xs.isDefined) xs else Some(List())
  y <- if(ys.isDefined) ys else Some(List())
} yield List(x,y).flatten

Scala Standard Library 2.12.2, Imagine you are reviewing a teammate's work in Scala when you are val opt = Option(1) val a = opt match { case Some(x) => x + 1 case None However, for list b , both b.forall(isPrime) and b.forall(!isPrime) are false. We are enthusiastic about newcomers def hello(name: Option[String]) Join Originate Associates. Strings in Scala are same as java string and hence the value is of type java.lang.String. Java classes are available in Scala, hence Scala makes use of java strings without creating a separate string class. Similar to Java, String is immutable in Scala i.e. the object cannot be modified. Creating String in Scala

Idiomatic Scala: Your Options Do Not Match, Let's write a generic function to combine two Option values , so that if any of those Let's try traverse out, by trying to parse a List[String] into a Option[List[Int]] :. import scala.util.control.Exception._ def readTextFile(f: String): Option[List[String]] = allCatch.opt(Source.fromFile(f).getLines.toList) allCatch is described as a Catch object “that catches everything.” The opt method returns None if an exception is caught (such as a FileNotFoundException), and a Some if the block of code succeeds.

Fp In Scala, def ownerDrivingLicense(car: Car): Option[Option[String]] = You can use the flatten function to combine two nested optional values as follows:. scala> import org.scalatest.Matchers._ import org.scalatest.Matchers._ scala> List.empty shouldBe empty scala> None shouldBe empty scala> Some(1) should not be empty scala> "" shouldBe empty scala> new java.util.HashMap[Int, Int] shouldBe empty scala> new { def isEmpty = true} shouldBe empty scala> Array(1, 2, 3) should not be empty

Using Option in Scala, Part 2: map and flatmap - Manning , def getSurnames(contacts: List[Contact]): List[String] = contacts.map(contact Apk map opaterion nx List cya z tbox iasrmli niiolamttepmne er rqo kon iddeenf kn Option. Abo ncoftnui getNumbers rruent hdrk cj List[List[ContactNumber]] . Hvroeew while the function flatten creates a list by combining two nested structures. This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.5, “How to Merge (Concatenate) Lists in Scala” Problem. You want to merge/concatenate the contents of two lists. Solution. Merge two lists using the ++, concat, or ::: methods. Given these two lists:

Comments
  • This does not return the correct value if both inputs are Some(List()). This should return Some(List()), but your solution returns None.
  • Does not produce the requested result if either input is None.
  • Right you are jwvh, I updated the answer to handle None
  • Alas, now it doesn't produce the requested result if both inputs are None.