Reputation: 1389
I have a list containing something like:
val lines: List[String] = List("bla blub -- id_1", "sdkfjdf -- id_2", "blubber blab -- id_1", "foo -- id_3", "ieriuer -- id_2", "bar -- id_3")
So basically the list contains an identifier which exists exactly twice (id_x) and a string which belongs to one of the identifiers.
I want to split that one list into two lists which then each contains a unique set of id_s with their belonging strings, like this:
l1("bla blub -- id_1", "sdkfjdf -- id_2", "foo -- id_3")
l2("blubber blab -- id_1", "ieriuer -- id_2", "bar -- id_3")
How would i do that in a functional way?
Best Regards, Sven
Upvotes: 3
Views: 2241
Reputation: 51109
lines.groupBy(_.split(" -- ")(1)).toList.map(_._2).transpose
That's the rough and ready way to do it; in reality if you want to do something more with this data it'll probably be better to parse the items into a case class, a la:
case class Item(id: String, text: String)
val items = for {
line <- lines
Array(text, id) = line.split(" -- ")
} yield Item(id, text)
then do the same as above, except groupBy(_.id)
, and conveniently sortBy(_.id)
as well.
Upvotes: 3
Reputation: 21567
How about this solution?
lines.groupBy(_.takeRight(3)).map(_._2).foldLeft((List.empty[String], List.empty[String])) {
(acc, elem) => elem match {
case left :: right :: Nil =>
(left :: acc._1, right :: acc._2)
case Nil => acc
}
}
res2: (List[String], List[String]) = (List(bla blub -- id_1, sdkfjdf -- id_2, foo -- id_3),List(blubber blab -- id_1, ieriuer -- id_2, bar -- id_3))
Upvotes: 1