cobra
cobra

Reputation: 35

Split a List[String] into separate list by a string

I am curious on how I can split a list of strings into separate lists based off another string.

val animals: Map[Int, List[String]] = Map(5 -> List("cat", "dog", "mouse", "bear", "lion"),
                                          (11 -> List("dog", "mouse", "tiger", "lion", "bear", "bird"),
                                          (9 -> List("mouse", "dog", "mouse", "tiger", "bear"),
                                          (15 -> List("cat", "tiger", "mouse")
                                      )

I am looking to use "mouse" to get similar output to this:

res0: Map[Int, List[String]] = Map(5 -> List(List("cat", "dog"), List("bear", "lion"))),
                                   (11 -> List(List("dog"), List("tiger", "lion", "bear", "bird"))),
                                   (9 -> List(List("dog"), List("tiger", "bear"))),
                                   (15 -> List(List("cat", "tiger")))
                               )

That is my exact case, more specifically I would just like to know a simple way I can split a general List[String] by a string.

Upvotes: 2

Views: 232

Answers (1)

jwvh
jwvh

Reputation: 51271

See if this gets at what you're after.

animals.map{case (k,lst) =>
  k -> lst.foldRight(List(List.empty[String])){
    case ("mouse", acc) => Nil::acc
    case (anml, hd::tl) => (anml::hd)::tl
  }.filter(_.nonEmpty)
}

Upvotes: 2

Related Questions