scala - Partioning a List into more than two partitions -
i have list:
val list1 = list("male:adam", "male:peter", "female:jane", "female:sue", "female:jo", "other:john")
i want create 2 lists, 1 of female names , 1 of male names. i.e.:
list("adam", "peter") list("jane", "sue", "jo")
i've done
val result = list1.groupby(_.startswith("male"))
so result
has 2 lists mapped against true
, false
each element being "male:adam"
etc. i'd have cycle through each list removing male:
, female:
strings. smells of non-functional.
can show how above problem solved in functional way?
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)
Comments
Post a Comment