设为首页 加入收藏

TOP

Scala简单计算实例,其在数据分析方面的优势体会
2017-10-10 12:13:19 】 浏览:5148
Tags:Scala 简单 计算 实例 数据分析 面的 优势 体会

程序只是简单的从文件中读取数据,并进行计算。

package com.bill.www

/**
  * Created by Bill on 2016/2/3.
  * 目的:用scala实现简单的数据计算
  * 源文件:接口记录条数20条,包括时间戳和浮点型数据
  * 执行方式:scala ReadFile.scala "E:\\spark\\data\\i_22_221000000073_L_20151016\\i_22_221000000073_L_20151016_223458.dat"
  * 开发环境:win10 + IJ IDEA15.0.2 + scala2.11.7 + java1.7
  */

import scala.collection.mutable
import scala.io.Source

object ReadFile {
  def main(args: Array[String]) {
    println("hello-------------------------------------------------------")

    // 读取文件并逐行打印其内容和长度
    if(args.length > 0) {
      for( line <- Source.fromFile(args(0)).getLines)
        print(line.length + "\t-- " +line + "\n")
    }
    else
      Console.err.println("Please enter a file or file with directory")

    println("--------------------------------------------------------1st.")

    // 用ArrayBuffer来存一列数据,通过对对象的一些操作来实现各种计算
    val nums = mutable.ArrayBuffer[Float]()
    if(args.length > 0) {
      for( line <- Source.fromFile(args(0)).getLines) {
        // 逐行处理
        // 拆分字段,类型转换,追加到可变数组
        nums += line.split(" ")(1).toFloat
      }
    }
    else
      Console.err.println("Please enter a file or file with directory")

    // 做一些简单的计算,并输出计算结果
    // common calculate
    println(nums.sum)
    println(nums.length)
    println(nums.max)
    println(nums.min)
    // average
    println(nums.sum/nums.length)
    println("--------------------------------------------------------2nd.")
    // sort desc
    nums.sorted.reverse foreach(println)

    println("--------------------------------------------------------end.")
  }
}

执行结果如下:

hello-------------------------------------------------------
21	-- 22:34:58.0000 23.9299
20	-- 22:34:58.0005 23.927
21	-- 22:34:58.0010 23.9277
21	-- 22:34:58.0015 23.9284
20	-- 22:34:58.0020 23.927
21	-- 22:34:58.0025 23.9256
20	-- 22:34:58.0030 23.927
20	-- 22:34:58.0035 23.927
21	-- 22:34:58.0040 23.9263
21	-- 22:34:58.0045 23.9284
21	-- 22:34:58.0050 23.9277
21	-- 22:34:58.0055 23.9263
21	-- 22:34:58.0060 23.9291
21	-- 22:34:58.0065 23.9256
21	-- 22:34:58.0070 23.9277
21	-- 22:34:58.0075 23.9256
21	-- 22:34:58.0080 23.9241
21	-- 22:34:58.0085 23.9263
20	-- 22:34:58.0090 23.927
21	-- 22:34:58.0095 23.9263
--------------------------------------------------------1st.
478.54
20
23.9299
23.9241
23.927
--------------------------------------------------------2nd.
23.9299
23.9291
23.9284
23.9284
23.9277
23.9277
23.9277
23.927
23.927
23.927
23.927
23.927
23.9263
23.9263
23.9263
23.9263
23.9256
23.9256
23.9256
23.9241
--------------------------------------------------------end.

 初学阶段的学习交流。

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Scalaz(27)- Inference & Unap.. 下一篇atitit.编程语言?类与对象的?扩展..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目