Reputation: 2812
I have a list:
val list1 = List("male:Adam", "male:Peter", "female:Jane", "female:Sue", "female:Jo", "other:John")
I want to create two lists, one of female names and one of male names. i.e.:
List("Adam", "Peter")
List("Jane", "Sue", "Jo")
I've done this with
val result = list1.groupBy(_.startsWith("male"))
So that result
has the two lists mapped against true
and false
but with each element being "male:Adam"
etc. But then I'd have to cycle through each list removing the male:
and female:
strings. This smells of non-functional.
Can anyone show how the above problem would be solved in a functional way?
Upvotes: 0
Views: 600
Reputation: 68750
val groups = list.map(_.split(":")).groupBy(_(0)).mapValues(_.map(_(1)))
val males = groups("male")
val females = groups("female")
Upvotes: 2
Reputation: 9820
val map = list1.map(s => s.split(":") match {
case Array(sex, name) => (sex, name)
})
.groupBy { case (sex, name) => sex }
.mapValues(_.map{ case (sex, name) => name })
val male = map("male")
// List(Adam, Peter)
val female = map("female")
// List(Jane, Sue, Jo)
Upvotes: 4