How to write single line scala codes? -


i'm new scala , i've written piece of code takes employee file(empid, name, age, salary, department) input , prints out department , total salary in department.

it novice code. how shorten code? please

code:

object usingcollectionmaps {   def main(a: array[string]) {     val filename = "employee.txt"     var map = collection.mutable.map[string,long]()     var sal: long = 0     (line <- source.fromfile(filename).getlines()) {       val fields = line.split(",")       if (map.contains(fields(4))) {         map.put(fields(4), (map(fields(4)) + fields(3).tolong))       } else {         map.put(fields(4), fields(3).tolong)       }     }     println(map)   } } 

i try avoid mutable structures , make sense of file, part case class. after that, use of groupby , sum.

import scala.io.source  case class employee(empid: string, name: string, age: int,                     salary: long, department: int)  source.fromfile("somefile.txt")       .getlines()       .map( _.split(",") )       .map( l => employee(l(0), l(1), l(2).toint,                           l(3).tolong, l(4).toint) )       .toseq       .groupby( _.department )       .mapvalues( _.map( _.salary ).sum ) 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -