Add Up Values in a Map with Multiple Lists in Scala -
i have map in scala in each key maps value list of indeterminate lists. aka map's type [string,list[list[string]]]
. need add third value (value3) of each list, in each map key. however, don't know how because each key has different number of lists in it's corresponding value. example:
map(string -> list(list(value1, value2, value3, value4), list(value1, value2, value3, value4), list(value1, value2, value3, value4)))
how go doing this?
you need default value in case 1 of lists has fewer 3 elements.
also, need define mean "add" since have strings. list or concatenate them in string.
you want key map values. drop 2 items each list optional third (none if list has fewer 3 items, some(x) otherwise). since flatmap, list of "third items" , can concatenate them or else.
val map = map("a" -> list(list("a", "b", "c", "d"), list("a", "b"), list("x", "y", "z"))) map.mapvalues(_.flatmap(_.drop(2).headoption)) // returns "a" -> list("c", "z") map.mapvalues(_.flatmap(_.drop(2).headoption).mkstring) // returns "a" -> "cz"
here more generic version in can fold on nth items of map of list of lists. it's not generic get, idea
def foldnth[a, r](xs: traversable[traversable[a]], n: int, z: r)(add: (r, a) => r) = xs.flatmap(_.drop(n).headoption).foldleft(z)(add) map.mapvalues(foldnth(_, 2, vector[string]())(_ :+ _)) // concatenates them in vector map.mapvalues(foldnth(_, 2, "")(_ + _)) // concatenates them in string
Comments
Post a Comment