如何编写单行scala代码?

时间:2015-07-21 19:10:08

标签: scala

我是Scala的新手,我写了一段代码,将员工档案(empId,姓名,年龄,薪水,部门)作为输入,打印出部门和部门的总薪水。

这是一个新手代码。如何缩短代码?请帮忙

代码:

object UsingCollectionMaps {
  def main(a: Array[String]) {
    val filename = "Employee.txt"
    var map = collection.mutable.Map[String,Long]()
    var sal: Long = 0
    for (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)
  }
}

3 个答案:

答案 0 :(得分:8)

我会尽量避免这些可变结构,并且也要理解这个文件,将它正确地分配给一个case类。 之后,使用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 )

答案 1 :(得分:4)

您可以使用.groupBy方法创建一个Map的部门&#39; - &GT; &#39;雇员&#39;然后总结他们的工资:

object UsingCollectionMaps {
  def main(a:Array[String]){
    val filename = "Employee.txt"
    val lines = io.Source.fromFile(filename).getLines().toList
    val map = employees.map(_.split(","))
                       .groupBy(_(4))  // Group by the fourth element of the arrays
                       .mapValues(_.map(_(3).toLong).sum) // Map an employeeList to their salaries and sum them
    println(map)
  }
}

答案 2 :(得分:3)

这不会短得多,但确实需要采用更实用的方法:

import collection.immutable.Map
import io.Source

object UsingCollectionMaps {
  def main(args: Array[String]) {
    println(
      Source.fromFile("Employee.txt").getLines()
        .foldLeft(Map.empty[String, Long])({
          case (totals, line) =>
            val fields = line.split(",")
            val department = fields(4)
            val salary = fields(3).toLong
            totals.updated(department, 
              totals.getOrElse(department, 0L) + salary)
        })
    )
  }
}