5,Scala数组操作实战详解

package com.dt.scala.hello

import scala.collection.mutable.ArrayBuffer

object ArrayOps {

  def main(args: Array[String]): Unit = {
    val nums = new Array[Int](10)
    val a = new Array[String](10)
    val s = Array("Hello", "World")
    s(0) = "Goodbye"

    val b = ArrayBuffer[Int]()
    b += 1
    b += (1, 2, 3, 5)
    b ++= Array(8, 13, 21)
    b.trimEnd(5)
    b.insert(2, 6)
    b.insert(2, 7, 8, 9)
    b.remove(2)
    // 从索引为2的位置移除三个元素
    b.remove(2, 3)
    b.toArray

    for (i <- 0 until a.length)
      println(i + ": " + a(i))

    val c = Array(2, 3, 5, 7, 11)
    // 左边是数组
    val result = for (elem <- c) yield 2 * elem
    for (elem <- c if elem % 2 == 0) yield 2 * elem
    // 等同上面的式子
    c.filter(_ % 2 == 0).map(2 * _)

    Array(1, 7, 2, 9).sum
    // 求长度最长
    ArrayBuffer("Mary", "had", "a", "little", "lamb").max

    // 排序
    val d = ArrayBuffer(1, 7, 2, 9)
    val bSorted = d.sorted

    // 快排
    val e = Array(1, 7, 2, 9)
    scala.util.Sorting.quickSort(e)

    // 数组之间连接符号
    e.mkString(" and ")
    // 头尾中间分别连接符号
    a.mkString("<", ",", ">")

    val matrix = Array.ofDim[Double](3, 4)
    matrix(2)(1) = 42
    val triangle = new Array[Array[Int]](10)
    for (i <- 0 until triangle.length)
      triangle(i) = new Array[Int](i + 1)
  }
}

信息来源于 DT大数据梦工厂微信公众账号:DT_Spark

网址:http://pan.baidu.com/share/home?uk=4013289088&view=share#category/type=0

你可能感兴趣的:(5,Scala数组操作实战详解)