zoukankan      html  css  js  c++  java
  • scala基础(二)

    scala中的数组

    定长数组:Array

    scala> val a = new Array[Int](10)
    		a: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
    

    初始化赋值,默认值是0
    未声明Array类型,直接赋值,Array的类型是any及任何类型都可以

    scala> val b = new Array[String](15)
    		b: Array[String] = Array(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null)
    
    		scala> val c = Array("Tom","Mary","Andy")
    		c: Array[String] = Array(Tom, Mary, Andy)
    
    		scala> val c = Array("Tom","Mary",1)
    		c: Array[Any] = Array(Tom, Mary, 1)
    

    注意:在声明Array时如果指定了类型那么数组元素就必须全部未该类型

    scala> val c:Array[String]=Array("Tom","Andy",1)
    		<console>:11: error: type mismatch;
    		 found   : Int(1)
    		 required: String
    			   val c:Array[String]=Array("Tom","Andy",1)
    

    变长数组:ArrayBuffer

    scala> import scala.collection.mutable._
    		import scala.collection.mutable._
    scala> val d = ArrayBuffer[Int]()
    		d: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
    

    注意:其中mutable代表可变
    其中数组的方法可以使用d.+tab见来查看

    scala> d.
    		++            clear           flatMap           isEmpty              permutations        segmentLength     toIterable
    		++:           clone           flatten           isTraversableAgain   prefixLength        seq               toIterator
    		++=           collect         fold              iterator             prepend             size              toList
    		++=:          collectFirst    foldLeft          last                 prependAll          sizeHint          toMap
    		+:            combinations    foldRight         lastIndexOf          product             sizeHintBounded   toSeq
    		+=            companion       forall            lastIndexOfSlice     readOnly            slice             toSet
    		+=:           compose         foreach           lastIndexWhere       reduce              sliding           toStream
    		-             contains        genericBuilder    lastOption           reduceLeft          sortBy            toString
    		--            containsSlice   groupBy           length               reduceLeftOption    sortWith          toTraversable
    		--=           copyToArray     grouped           lengthCompare        reduceOption        sorted            toVector
    		-=            copyToBuffer    hasDefiniteSize   lift                 reduceRight         span              transform
    		/:            corresponds     hashCode          map                  reduceRightOption   splitAt           transpose
    		:+            count           head              mapResult            reduceToSize        startsWith        trimEnd
    		:            diff            headOption        max                  remove              stringPrefix      trimStart
    		<<            distinct        indexOf           maxBy                repr                sum               union
    		WithFilter    drop            indexOfSlice      min                  result              tail              unzip
    		addString     dropRight       indexWhere        minBy                reverse             tails             unzip3
    		aggregate     dropWhile       indices           mkString             reverseIterator     take              update
    		andThen       endsWith        init              nonEmpty             reverseMap          takeRight         updated
    		append        equals          inits             orElse               runWith             takeWhile         view
    		appendAll     exists          insert            padTo                sameElements        to                withFilter
    		apply         filter          insertAll         par                  scan                toArray           zip
    		applyOrElse   filterNot       intersect         partition            scanLeft            toBuffer          zipAll
    		canEqual      find            isDefinedAt       patch                scanRight           toIndexedSeq      zipWithIndex
    

    数组的常见操作:
    1.添加元素:使用+=即可

    scala> d += 1
    		res8: d.type = ArrayBuffer(1)
    
    		scala> d += 2
    		res9: d.type = ArrayBuffer(1, 2)
    
    		scala> d += 3
    		res10: d.type = ArrayBuffer(1, 2, 3)
    
    		scala> d += (4,5,6,7)
    		res11: d.type = ArrayBuffer(1, 2, 3, 4, 5, 6, 7)
    

    2.去掉数组中最后两个元素

    scala> d.trimEnd(2)
    
    		scala> d
    		res13: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5)
    

    3.遍历数组(使用for循环和数组自带的foreach函数)

    scala> var a = Array("Tom","Andy","Mary")
    			a: Array[String] = Array(Tom, Andy, Mary)
    
    			scala> for(s<-a) println(s)
    			Tom
    			Andy
    			Mary
    
    			scala> a.foreach(println)
    			Tom
    			Andy
    			Mary
    

    4.最大值最小值和排序

    scala> val myarray = Array(1,2,7,8,10,3,6)
    			myarray: Array[Int] = Array(1, 2, 7, 8, 10, 3, 6)
    
    			scala> myarray.max
    			res16: Int = 10
    
    			scala> myarray.min
    			res17: Int = 1
    
    			scala> myarray.sortWith(_>_)
    			res18: Array[Int] = Array(10, 8, 7, 6, 3, 2, 1)
    
    			scala> myarray.sortWith(_<_)
    			res19: Array[Int] = Array(1, 2, 3, 6, 7, 8, 10)
    			
    

    注意:其中myarray.sortWith(_>_)就相当myarray.sortWith((a,b)=>{if(a>b) true else false})
    (a,b)=>{if(a>b) true else false} 是匿名函数,没有名字,传入两个参数 a b,返回值是bool
    sortWith(>) 是高阶函数,即参数是函数

    多维数组:和Java一样通过数组的数组来实现

    定义一个固定长度的二维数组

    scala> val matrix = Array.ofDim[Int](3,4)
    		matrix: Array[Array[Int]] = Array(
    		Array(0, 0, 0, 0), 
    		Array(0, 0, 0, 0), 
    		Array(0, 0, 0, 0)
    		)
    		
    		scala> matrix(1)(2)=10
    
    		scala> matrix
    		res21: Array[Array[Int]] = Array(
    		Array(0, 0, 0, 0), 
    		Array(0, 0, 10, 0), 
    		Array(0, 0, 0, 0))
    

    定义一个变长的二维数组:

    scala> var triangle = new Array[Array[Int]](10)
    		triangle: Array[Array[Int]] = Array(null, null, null, null, null, null, null, null, null, null)
    
    		scala> for(i <- 0 until triangle.length)
    			 | triangle(i)=new Array[Int](i+1)
    
    		scala> triangle
    		res23: Array[Array[Int]] = Array(
    		Array(0), 
    		Array(0, 0), 
    		Array(0, 0, 0), 
    		Array(0, 0, 0, 0), 
    		Array(0, 0, 0, 0, 0), 
    		Array(0, 0, 0, 0, 0, 0), 
    		Array(0, 0, 0, 0, 0, 0, 0), 
    		Array(0, 0, 0, 0, 0, 0, 0, 0), 
    		Array(0, 0, 0, 0, 0, 0, 0, 0, 0), 
    		Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
    

    映射:就是<Key, Value>,用map表示

    scala中map有两种:一种是不可变的map,第二种是可变的map
    scala.collection.mutable.Map 是可变的Map
    scala.collection.immutable.Map 是不可变Map
    声明一个不可变的map:

    scala> val scores2 = scala.collection.immutable.Map("Tom" -> 80, "Mary"->77,"Mike"->82)
    	scores2: scala.collection.immutable.Map[String,Int] = Map(Tom -> 80, Mary -> 77, Mike -> 82)
    

    另一种声明方式:

    scala> val chineses = Map(("Tom",80),("Mary",60),("Lily",50))
    	chineses: scala.collection.mutable.Map[String,Int] = Map(Tom -> 80, Lily -> 50, Mary -> 60)
    

    映射的操作:

    1.获取映射中的值

    首先判断key是否存在

    scala> if(chineses.contains("To123123m")){
    			 | chineses("To123123m")
    			 | } else {
    			 | 1}
    		res27: Int = 1
    
    		scala> chineses.getOrElse("To123123m",-1)
    		res28: Int = -1
    		
    		scala> chineses.get("dlfsjldkfjlsk")
    		res29: Option[Int] = None
    
    

    使用get方法时不会报错;

    scala> chineses.get("Tom")
    		res30: Option[Int] = Some(80)
    

    2.更新映射中的值

    scala> chineses
    			res31: scala.collection.mutable.Map[String,Int] = Map(Tom -> 80, Lily -> 50, Mary -> 60)
    
    			scala> chineses("Tom")
    			res32: Int = 80
    
    			scala> chineses("Tom")=100
    
    			scala> chineses
    			res34: scala.collection.mutable.Map[String,Int] = Map(Tom -> 100, Lily -> 50, Mary -> 60)
    

    3.映射中的迭代:可以使用foreach,foreach本身就是一个高阶函数

    scala> chineses
    			res35: scala.collection.mutable.Map[String,Int] = Map(Tom -> 100, Lily -> 50, Mary -> 60)
    
    			scala> for(s <- chineses) println(s)
    			(Tom,100)
    			(Lily,50)
    			(Mary,60)
    
    			scala> chineses.foreach(println)
    			(Tom,100)
    			(Lily,50)
    			(Mary,60)
    

    元组:Tuple

    scala中的Tuple是代表不同类型的元素集合
    声明:

    scala> val t1 = Tuple(1,0.3,"Hello")
    	<console>:14: error: not found: value Tuple
    		   val t1 = Tuple(1,0.3,"Hello")
    					^
    
    	scala> val t1 = Tuple3(1,0.3,"Hello")
    	t1: (Int, Double, String) = (1,0.3,Hello)
    	
    

    其中Tuple3代表Tuple中有三个元素
    也可以如此声明

    scala> val t1 = (1,0.3,"Hello")
    	t1: (Int, Double, String) = (1,0.3,Hello)
    
    	scala> val t1 = (1,0.3,"Hello",1,12,5,"all")
    	t1: (Int, Double, String, Int, Int, Int, String) = (1,0.3,Hello,1,12,5,all)
    

    Tuple中的方法 主要有:

    scala> t1.
    	_1   _3   _5   _7         copy     hashCode       productElement    productPrefix
    	_2   _4   _6   canEqual   equals   productArity   productIterator   toString
    

    其中可以根据_n来获取对应位置的元素

    scala> t1._1
    	res38: Int = 1
    
    	scala> t1._3
    	res39: String = Hello
    

    在Tuple中是没有foreach方法的,所以我们需要先使用productIterator来创建迭代之后在使用foreach

    scala> t1.productIterator.
    	++                corresponds   foldRight            max         reduceLeft          span           toSeq
    	/:                count         forall               maxBy       reduceLeftOption    sum            toSet
    	:                drop          foreach              min         reduceOption        take           toStream
    	GroupedIterator   dropWhile     grouped              minBy       reduceRight         takeWhile      toString
    	addString         duplicate     hasDefiniteSize      mkString    reduceRightOption   to             toTraversable
    	aggregate         exists        hasNext              next        sameElements        toArray        toVector
    	buffered          filter        indexOf              nonEmpty    scanLeft            toBuffer       withFilter
    	collect           filterNot     indexWhere           padTo       scanRight           toIndexedSeq   zip             dex
    	collectFirst      find          isEmpty              partition   seq                 toIterable     zipAll
    	contains          flatMap       isTraversableAgain   patch       size                toIterator     zipWithIndex
    	copyToArray       fold          length               product     slice               toList
    	copyToBuffer      foldLeft      map                  reduce      sliding             toMap
    	res13: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5)
    	scala> t1.productIterator.foreach(println)
    	1cala>
    	0.3
    	Hello
    	1
    	12
    	5
    	all
    

    scala中的文件操作:

    类似于java中的io操作

    1.读取文件

    2.读取二进制文件

    3.从url中获取信息

    4.写入文件

    5.scala中调用java类

    package day0601
    
    /**
      * Created by root on 2019/6/1.
      *
      * scala中的io
      *
      */
    import java.io.{File, FileInputStream, PrintWriter}
    import scala.io.Source._
    object IODemo {
      def main(args: Array[String]): Unit = {
    
        //读取行
        val source = fromFile("H:\tmp_files\student.txt")
    
        /**
          * 1、将整个文件作为字符串输出
          *
          * 2、将文件的每一行读入 java BufferedReader readLine方法类似
          */
        println("--------mkString---------")
    //    println(source.mkString)
        println("--------lines---------")
    //    val lines = source.getLines()
    //    lines.foreach(println)
    
        /**
          * 如果实验第二个方法的时候,第一个方法没有注释掉,那第二个方法不会有输出值
          * 原因:文件在第一个方法时,已经被读取过
          * 和Java一样
          */
    
        //读取字符
    //    for (c <- source) println(c)
        println("--------fromURL---------")
    //    var source2 = fromURL("https://www.baidu.com","UTF-8")
    //    println(source2.mkString)
    
        /**
          * 读取二进制文件:
          * scala中并不支持直接读取二进制
          * 可以通过调用java的InputStream来进行读入
          */
        println("--------Read Bytes---------")
        var file = new File("H:\tmp_files\hudson.war")
        //构建一个inputstream
        var in = new FileInputStream(file)
        //构造buffer
        var buffer = new Array[Byte](file.length().toInt)
        //读取
        in.read(buffer)
        println(buffer.length)
        //关闭
        in.close()
    
        /**
          * 写入文件
          */
        println("--------Write File---------")
        var out = new PrintWriter("H:\tmp_files\insert_0601.txt")
        for (i <- 0 until 10) out.println(i)
        out.close()
    
    
      }
    }
    
    
  • 相关阅读:
    python socket 二进制
    全面介绍内存管理机制
    glog修改
    mysql c api
    http twisted
    IOCP 模型1
    IOCP 模型2 AcceptEx
    python
    Python Twisted
    Java 拾遗
  • 原文地址:https://www.cnblogs.com/yjfb/p/12488448.html
Copyright © 2011-2022 走看看