Scala collection mapping operations map, reduce, filter, etc.

Higher order function

A function that can accept a function as a parameter becomes a higher-order function
Example

    //test 是一个高阶函数,可以接受一个(入参double返回值double)函数,和一个double参数
  def test(f:Double=>Double,n1:Double) ={
    
    
    f(n1)
  }
  //普通函数 接受double返回double
  def sum2(d:Double):Double={
    
    
    println("翻倍函数被调用~~")
    return d+d
  }

  //高阶函数 接受一个无入参无返回值的函数
  def test2(f:()=>Unit)= {
    
    
    f()
  }
  //普通函数
  def sayOk()={
    
    
    println("ok~~~")
  }
  def main(args: Array[String]): Unit = {
    
    
    //使用示例1
     val ttt=test(sum2 ,3.5)
     println(ttt)//7.0
    //使用示例2
    test2(sayOk)
  }

map mapping operation

Map mapping operation collection element example

 var list =List(1,2,3);
      def dble(p:Int):Int={
    
    
        p+p
      }
      var list2 = list.map(dble)
      println(list)//List(1, 2, 3)
      println(list2)//List(2, 4, 6)

What does list.map(dble) do
1) Traverse the list collection in turn
2) Pass each element to the dble function to get a new element
3) Put the obtained new element in a new collection and return

flatMap mapping

flatmap mapping flat flattening and flattening
The mapping effect is to map the child elements of each element in the combination to a function and return a new set.
Example

  var names = List("Alice","Bob","Nick");
  def upper(p:String):String={
    
    
    p.toUpperCase()
  }
  var names2 = names.flatMap(upper)
  println(names2)//List(A, L, I, C, E, B, O, B, N, I, C, K)

filter

Put the elements that meet the requirements into the new collection, an example is as follows:

 def startsA(str:String):Boolean={
    
    
   str.startsWith("A")
 }
 var names3 = names.filter(startsA)
 println(names3)//List(Alice)

reduce

将二元函数应用于集合中的元素
def sum (a:Int,b:Int): Int ={
    
    
  a+b
}
var l1= List(2,3,4,5);
var res = l1.reduceLeft(sum)
println("res:"+res) //res:14

fold

The fold function uses the return value of the previous step as the first parameter of the function to continue to pass and operate until all the elements in the list are traversed.
Can reduceLeft be regarded as a simplified version of foldLeft related functions: fold foldLeft foldRight
example

    def minus(n1:Int,n2:Int): Int ={
    
    
      n1-n2
    }
    /*
    步骤分析:
    println(l1.foldLeft(5)(minus)) 效果等同于 list(5,2,3,4,5) list.reduceLef(minus)
    1.5-2=3
    2.3-3=0
    3.0-4=-4
    4.-4-5=-9
     */
    println(l1.foldLeft(5)(minus))//-9
    /*
   步骤分析:
   println(l1.foldRight(5)(minus)) 效果等同于 list(2,3,4,5,5) list.reduceRight(minus)
   1.5-5=0
   2.4-0=4
   3.3-4=-1
   4.2-(-1)=3
    */
    println(l1.foldRight(5)(minus)) //3

//foldLeft 和 foldRight 缩写方法是 /: 和 :\ 编辑器提示已过期

scan

Perform a fold operation on all elements in a certain collection, but will store all intermediate results produced in a collection

//过程  5(1,2,3,4,5)  (5,4,2,-1,-5,-10)
val i8 =(1 to 5).scanLeft(5)(minus)
println(i8)//Vector(5, 4, 2, -1, -5, -10)
//过程  (1,2,3,4,5)5  (20, 19, 17, 14, 10, 5  )
val i9 =(1 to 5).scanRight(5)(sum)
println(i9)//Vector(20, 19, 17, 14, 10, 5)

zip

In development, when we need to combine two sets into dual element combinations, we can use zippers.
Notes on using zippers
1) The essence of zippers is the merging operation of two sets. After the elements are merged, a dual tuple is programmed.
2) If two sets are combined If the numbers do not correspond to each other, it will cause data loss.
3) The set is not limited to List, but can also be other sets such as Array.
4) If you want to retrieve the data of the combined dual tuples, you can traverse.
Example

val ll1=List(1,2,3);
val ll3 = List("one","tow","three");
val ll4 = ll1.zip(ll3)
println(ll4)//List((1,one), (2,tow), (3,three))

Iterator

Obtain an iterator from the collection through the iterator method, and traverse through the while loop and the for expression

Example

var iter01= List(1,2,3,4,5).iterator
while(iter01.hasNext){
    
    
  println(iter01.next())
}
iter01= List(1,2,3,4,5).iterator
for(item<-iter01){
    
    
  println(item)
}

Stream

A stream is a collection. This collection can be used to store infinite elements, but these infinite elements will not be produced at once.
Instead, it will be dynamically produced as long as the interval is used. The last elements follow the lazy rule.

Example

  //Stream 集合存放的数据类型是BigInt
    //numsForm 是一个自定义的函数,创建的集合第一个元素时n ,后续元素生成规则是 N+1
    //后续元素生成规则是可以指定的 比如 numsForm(n*4)
     def numsForm(n:BigInt):Stream[BigInt] = n #::numsForm(n+1)
     val stream1 = numsForm(1)
      println(stream1)//Stream(1, ?)
     println("stream1.head="+stream1.head)//1
     println("stream1.tail="+stream1.tail)//stream1.tail=Stream(2, ?)
    println(stream1)//Stream(1, 2, ?)

View

With the lazy loading feature of Stream, you can also apply the view method to other collections to get a similar effect.
1) The view method produces a collection that is always executed lazily.
2) The view does not cache data and must be recalculated each time, for example When traversing

   def multi(num:Int):Int={
    
    
      num
    }

    //方法 如果翻转后 和原来相等 返回true 否则 返回false
   def eq(i:Int):Boolean={
    
    
      println("eq 被调用....")
      i.toString.equals(i.toString.reverse)
    }
  //不使用view
   val viewSquare = (1 to 100).filter(eq)
    println(viewSquare)
    val viewSquare2 = (1 to 100).view.filter(eq)
    println(viewSquare2)
    //遍历
    for(item <- viewSquare2){
    
    
      println("item:"+item)
    }

Parallel collection

1) In order to make full use of multi-core CPU, scala provides a parallel set for parallel computing in a multi-core environment.
2) The main algorithms used are
a) divide and conquer: divide and conquer algorithm. Scala uses a decomposer and a combiner to calculate tasks Decomposed into many tasks, distributed to some processors to complete,
and their processing results are combined and returned
b) work stealin work stealing algorithm, mainly used for task scheduling load balancing, after a thread completes its own work, it can continue to process other The thread is the completed work.

val resul1 = (0 to 100).map{
    
    case_ => Thread.currentThread().getName}.distinct
val resul2 = (0 to 100).par.map{
    
    case_ => Thread.currentThread().getName}.distinct
println(resul1);//非并行
println("-------------------")
println(resul2)//并行

Operator

Note
1) If you want to use grammatical keywords in the definition of variable names, class names, etc., you can use it with translation, such as val val= ""
2) The inset operator A and operator B are equivalent to A. Operator (B)
3 ) Post-operator: A operator is equivalent to A. Operator
4) Pre-operator: +, -,! And other operators A is equivalent to A.unary_ operator
5) Copy operator: A operator=B Equivalent to A=A operator B,

    var n1 =1;
     var n2 = 3;
    val r1 = n1+n2//3
    val r2=n1.+(n2)//3
    val mon = new Monster
    mon+10
    mon.+(10)
    println("money:"+mon.money)//20

    println(mon++)
    println(mon.++)
    println("money:"+mon.money)//22
    !mon
    println("money:"+mon.money)//-22

  class Monster{
    
    
    var money:Int =0
    //对+操作符进行重载
    def +(n:Int): Unit ={
    
    
      this.money+=n
    }

    def ++(): Unit ={
    
    
      this.money+=1
    }

    def unary_!(): Unit ={
    
    
      this.money = -this.money
    }

  }

Guess you like

Origin blog.csdn.net/zhangxm_qz/article/details/107641893