List深入浅出之基本语法与源码分析

场景
List基本语法、源码分析(后续补充)
参考文献

scala 深入浅出实战经典 . 王家林

实验

package com.scode.scala
import java.util.Queue
/**
 * author: Ivy Peng
 * function: List学习
 * date:2016/03/26 23.00
 */
object HelloList
{
  def main(args: Array[String]): Unit =
  {
    println(mergedSort((x:Int,y:Int)=> x<y)(List(5,7)))
    var reversed_mergedsort= mergedSort((x:Int,y:Int)=>x>y)_
    println(reversed_mergedsort(List(5)))
  }
  
  def Map_Set
  {
    val data = scala.collection.mutable.Set.empty[Int]
    data++=List(1,2,3)
    data+=4
    data --=List(2,3)
    println(data)
    data+=1
    data.clear
    println(data)
    
    val map = scala.collection.mutable.Map.empty[String,String]
    map("Java")="Hadoop"
    map("Scala")="Spark"
    println(map)
    println(map("Scala"))
    
    val treeSet = scala.collection.mutable.TreeSet(3,3,2,5)
    println(treeSet)
    val treeSetForChar = scala.collection.mutable.TreeSet("Hadoop","Spark","Atorm")
    println(treeSetForChar)
    
    var treeMap = scala.collection.immutable.TreeMap("Scala" -> "Spark","Java" -> "Hadoop")
    println(treeMap)
  }
  def ArrayBuffer_ListBuffer_Stack_Queue
  {
    import scala.collection.mutable.ListBuffer
    val listBuffer = new ListBuffer[Int]
    listBuffer+=1
    listBuffer+=2
    println(listBuffer)
    
    import scala.collection.mutable.ArrayBuffer
    val arrayBuffer = new ArrayBuffer[Int]
    arrayBuffer+=2
    arrayBuffer+=3
    println(arrayBuffer)
    
    import scala.collection.mutable.Queue
    val empty = Queue[Int]()
    empty.enqueue(1,2)
    println(empty)
    val head = Queue[Int](2,3,4,5).dequeue
    println(head)
    
    import scala.collection.mutable.Stack
    val stack = new Stack[Int]
    stack.push(2)
    stack.push(3)
    
    println(stack.top)
    println(stack)//Stack(3, 2)
    println(stack.pop)//println(stack.top)
    println(stack)
  }
  
  def ListOpsSix
  {
    println(List.apply(1,2,3))
    println(List.fill(3,2)(2))//List(List(2, 2), List(2, 2), List(2, 2))
    println(List.range(1,5))
    
    val zipped = "abcd".toList zip List(1,2,3,4)
    println(zipped)
    println(zipped.unzip)
    
    println(List(List('a','b'),List('c'),List('d','e')).flatten)
    println(List.concat(List(),List('b'),List('c')))
  }
  /**
   * foldLeft操作
   * foldRight操作:Applies a binary operator to all elements of this range and a start value, going right to left.
   * sortWith :Sorts this list according to a comparison function.
   * 
   */
  def ListOpsFive
  {
    println((1 to 100).foldLeft(0)(_+_))
    println(Range(1,100).foldLeft(0)(_+_))
    println((0/:(1 to 100))(_+_))
    
    println((1 to 5).foldRight(100)(_-_))
    println(((1 to 5):\100)(_-_))
    
    println(List(1,-3,4,2,8)sortWith(_<_))
    println(List(1,-3,4,2,8)sortWith(_>_))
  }
  /**
   * List基本操作之
   * partition
   * find
   * takeWhile
   * dropWhile
   * span
   */
  def ListOpsFour
  {
    println(List(1,2,3,4,5) partition(_%2==0))//Partitions this list in two lists according to a predicate. 
    println(List(1,2,3,4,5)find(_%3==0))//an option value containing the first element in the list that satisfies p, or None if none exists.
    println(List(1,2,3,4,5)find(_<3))
    println(List(1,2,3,4,5)takeWhile(_<3))
    println(List(1,2,3,4,5)dropWhile(_<3))
    println(List(1,2,3,4,5,6)span(_ <4))//(List(1, 2, 3),List(4, 5, 6))
   
    def hasZeroRow(m:List[List[Int]])= m exists(row=>row forall(_>0))
    val m = List(List(1,2,3),List(2,3,4),List(5,6,9))
    println(hasZeroRow(m))
  }
  
  /**
   * map 操作
   * flatMap操作
   * foreach操作
   * filter操作
   */
  def ListOpsThree
  {
    println(List(1,2,3)map (_ + 1)) //Builds a new collection by applying a function to all elements of this list
    println(List(1,2,3)map (item => item+1))
    val data = List("hadoop","spark","scala")
    println(data map(_.length))
    println(data map(_.toList.reverse.mkString))
    
    println("test map :"+data.map(_.toList))//List(List(h, a, d, o, o, p), List(s, p, a, r, k), List(s, c, a, l, a))
    
    println("test flatMap :"+data.flatMap(_.toList))//
    
    println(List.range(1,10)flatMap(i=>List.range(1,i)map(j=>(i,j))))
    //List((2,1), (3,1), (3,2), (4,1), (4,2), (4,3), (5,1), (5,2), (5,3), (5,4), (6,1), (6,2), (6,3), (6,4), (6,5), (7,1), (7,2), (7,3), (7,4), (7,5), (7,6), (8,1), (8,2), (8,3), (8,4), (8,5), (8,6), (8,7), (9,1), (9,2), (9,3), (9,4), (9,5), (9,6), (9,7), (9,8))
    
    var sum=0
    List(1,2,3,4,5).foreach(sum+=_)
    println(sum)
    println(List(1,2,3,4).filter(_%2==0))
    println(data.filter(_.length==5))
  }
  
  //归并排序实现
    def mergedSort[T] (less:(T,T)=> Boolean)(input:List[T]):List[T]=
    {
      /**
       * xList 要合并的有序列表
       * yList 要合并的有序列表
       * return 要合并的有序列表
       */
      def merge(xList:List[T],yList:List[T]):List[T] = 
        (xList,yList) match
      {
        case (Nil,_) => xList 
        case (_,Nil) => yList 
        case(x::xtail,y::ytail)=>
          if(less(x,y)) x::merge(xtail,yList)
          else y::merge(xList,ytail)
      }
      
      val n = input.length/2
      if(n==0) input //处理input长度为 0,1
      else
      {
        val (x,y) = input splitAt n //input长度> 1的情况,eg、2,1,4,6;把 要排序的input列表平均分成两个列表
        merge(mergedSort(less)(x),mergedSort(less)(y))//先对分后的两个列表归并排序,再对排好的有序列表进行归并
      }
    }
  def listOpsTwo
  {
    //list的链接
    println(List(1,2,3):::List(4,5,6):::List(3,6,9))
    println(List(1,2,3):::(List(4,5,6):::List(3,6,9)))
    println(List(1,2,3).length)
    
    //list常用操作
    val bigData = List("Hadoop","Spark","Kaffka")
    println(bigData.last)
    println(bigData.head)
    println(bigData.tail)//Selects all elements except the first. 
    println(bigData.init)//Selects all elements except the last. 
    println(bigData.reverse)//Returns new list with elements in reversed order.
    println(bigData)
    println(bigData take 2)//Selects first n elements. 
    println(bigData drop 2)//Selects all elements except first n ones.
    println(bigData splitAt 2)
    println(bigData apply 2)
    println(bigData(2))
    
    val data=List('a','b','c','d','e','f')
    println(data.indices)  // Produces the range of all indices of this sequence.
    println(data.indices zip data) 
    println(data.zipWithIndex) //Zips this list with its indices
    
    //list与String表示
    println(data.toString) //Converts this list to a string. eg、List(1,2,3,4)
    println(data.mkString("[",",","]")) //List(1, 2, 3).mkString("(", "; ", ")") = "(1; 2; 3)"
    println(data.mkString(" "))
    println(data.mkString)
    val buffer = new StringBuilder
    data addString(buffer,"(",";;",")")
    println(buffer)
    
    //List与数组的转换
    val array = data.toArray
    println(array.toList)
    val new_Array = new Array[Char](10)
    data.copyToArray(new_Array,3)
    new_Array.foreach(println)
    
    println
    //list的遍历
    val iterator = data.toIterator
    println(iterator.next)
    println(iterator.next)
  
  }
  def listOpsOne
  {
    //list的定义
    val bigdata = List("Spark","Hadoop","Player")
    val bigData2 = "Hadoop"::"Spark"::Nil
    val bigData3 = "Hadoop"::("Spark"::Nil)
    val intdata = List(1,2)

    println(bigdata.isEmpty)
    println(bigdata.head)
    println(bigdata.tail.head)
  
    //list的赋值
    val List(a,b,c)=bigdata //list(a,b)=bigdata则抛 scala.MatchError
    println("a=" + a + " b=" + b)
    val x::y::rest = bigData2
    println("a=" + a + " b=" + b + " rest=" + rest)
    
    //应用
    val shuffledData = List(1,3,2,1,79)
    println(sortList(shuffledData))
    
    def sortList(list:List[Int]):List[Int]= list match
    {
      case List()=> List()
      case head::tail => compute(head,sortList(tail))
    }
    
    def compute(data:Int,dataSet:List[Int]):List[Int]= dataSet match
    {
      case List() => List(data)
      case head::tail => 
         if(data<=head) data::dataSet
            else head::compute(data,tail)
    }
  }
}


你可能感兴趣的:(List深入浅出之基本语法与源码分析)