Group a Scala list by custom logic -
i have custom logic group list of names first letter , can achieve following:
val names = list("adam", "barbara", "bob", "charlie", "damien", "elaine", "florence", "gwen") names.map{ case x if x.startswith("a") => (1, x) case x if x.startswith("b") => (1, x) case x if x.startswith("c") => (2, x) case x if x.startswith("d") => (2, x) case x if x.startswith("e") => (3, x) case x if x.startswith("f") => (3, x) case default => (0, default) }.groupby(_._1)
the logic may change. example, next time may want group names starting a, f , g group 1 or may add letters z. more advanced logic take first 2 letters , group names starting ad , ba group 1, in case adam , barbara in same group.
i'd know if there more idiomatic approach, can write startswith
lesser number of times.
from tanjin's answer, further refactored groups
to:
val groups = list( (list("a", "b"),1), (list("c", "d"),2), (list("e", "f"),3) ).flatmap{ case (l,i) => l.map((_, i)) }
we can try - need alter groups
:
def categorize(groups: seq[(string, int)]) = (s: string) => { groups.find(category => category._1 == s.head.tostring) .map(c => (c._2, s)).getorelse((0, s)) } val groups = seq(("a", 1), ("b", 1), ("c", 2), ("d", 2), ("e", 3), ("f", 3)) names.map(categorize(groups)).groupby(_._1)
Comments
Post a Comment