functional programming - Filter list with two criteria and create a map scala -


i have case class keeps transactions(assume fund transfers). sake of simplicity use below one

case class trans(from: string, to: string, amount: int) 

i have list of transactions

val tl = list(   trans("a", "b", 30),    trans("a", "c", 40),   trans("b", "c", 10),   trans("b", "a", 25),   trans("c", "a", 15) ) 

i want group list based on from , to. needs take sum of groups map. map keeps elements in below structure

("a" -> (70, 40)) // "a" key // "70" sum of values "a" 'from' (30 + 40) // "40" sum of values "a" 'to' (25 + 15) 

for instance list should populate output

map("a" -> (70, 40), "b" -> (35, 30), "c" -> (15, 50)) 

i can filtering 2 statements , combine them below

// out map val mout = tl.map(t => (t.from, t.amount)).groupby(_._1).map(s => (s._1, s._2.sum))  // in map val min = tl.map(t => (t.to, t.amount)).groupby(_._1).map(s => (s._1, s._2.sum))  // can join these tow maps have final output 

are there way single/one statement?

if you're cats or scalaz user, can use foldmap:

import cats._, implicits._ // or... //import scalaz._, scalaz._   case class trans(from: string, to: string, amount: int)  val tl = list(   trans("a", "b", 30),    trans("a", "c", 40),   trans("b", "c", 10),   trans("b", "a", 25),   trans("c", "a", 15) )  tl foldmap {     case trans(from, to, am) => map(from -> (am, 0), -> (0, am)) } 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -