Scala Tutorial (12) List operation Advanced Combat __scala Tutorial

Source: Internet
Author: User
Tags scala tutorial

Scala Tutorial (12) List Operation Advanced Advance combat


1 List Basic Operation


1.1 List Composition Structure

The array is composed of the head tail two parts: head represents the first element, and tail represents the other elements.

    Val bigdata = List ("Hadoop", "Spark")
    val data = List (1,2,3)
    
    //array consists of head tail two parts: head represents the first element, tail represents other elements
    Val bigdatacore = "Hadoop":: ("Spark":: Nil);
    Val dataint = 1:: 2:: 3:: Nil
    
    //Is empty
    println (data.isempty);
    The first element:  1
    println (data.head)
    //Other elements: 2,3
    println (data.tail);
    
    
    Extracts the element content in the Bigdata, the element length in the array, must be consistent with the parameter in list ()
    val list (a,b) = Bigdata;
    Implementation results: A=hadoop,b=spark
    println ("a=" +a+ ", b=" +b);
    
    The first element, the second element, and the rest of the elements and List
    val x::y::rest = data
    //Execution Result: x=1,y=2,rest=list (3)
    println ("x=" +x+ ", y=" + y+ ", rest=" +rest);
1.2 list pattern matching

  def main (args:array[string]): unit = {
    //pattern matching
    val shuffleddata = List (6, 3, 5, 6, 2, 9, 1)
    println (Sortlist ( Shuffleddata)

    //Sort
    def sortlist (Dataset:list[int]): list[int] = dataSet 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);
      If the first element value of the collection is less than the data value, data is placed in the first position:
      tail => if (data <= head) data:: DataSet
      //If not less than the data value, proceed next time Compare
      else head:: Compute (data, tail);
    }
  
1.3::-Operator

Connectors::: To connect between list and list.

    Connector between list and list:::
    println (List (1,2,3,4)::: List (4,5,6,7,8)::: List (10,11));
    println (List (1,2,3,4):::(list (4,5,6,7,8)::: List (10,11));
    println (List (1,2,3,4)::: List (4,5,6,7,8)::: List (10,11));
    
    Lenght method particularly slow
    println (List (1,2,3,4). Length)
1.4 List First Order function operation
    var bigdata = List ("Hadoop", "Spark", "Kaffka")//last element, execution result: Kaffka println (Bigdata.last);
    In addition to the elements outside the last element, the result: List (Hadoop, Spark) println (bigdata.init);
    Inverted content, Execution results: List (Kaffka, Spark, Hadoop) println (bigdata.reverse)//print out itself, execution results: List (Hadoop, Spark, Kaffka)
    println (Bigdata)//Get the first two elements, execution results: List (Hadoop, Spark) println (Bigdata.take (2))//delete the first 22 elements, execution results: List (Kaffka) println (Bigdata.drop (2))//is broken into, the front two is a group, followed by a group of elements, execution results: (List (Hadoop, Spark), List (Kaffka)) println (Bigdata Splita
    T (2)); Getting elements by index: Index starts at 0, results: Kaffka println (Bigdata apply (2)) println (Bigdata (2))//Declaration list Val data = Lis
    T (' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G ');
    Gets the index of all the elements, execution results: Range (0, 1, 2, 3, 4, 5, 6) println (data.indices);
    Zip pairing combination operations, execution results: Vector ((0,a), (1,b), (2,c), (3,d), (4,e), (5,f), (6,g)) println (data.indices zip data); Zip pairing combination operation, execution results: List ((a,0), (b,1), (c,2), (d,3), (e,4), (f,5), (g,6)) println (Data.zipwithIndex);
    ToString method, execution Result: List (A, B, C, D, E, F, g) println (data.tostring ());
    Returns both ends with brackets at the beginning, end, and middle separated by semicolons, executing the result: [A;b;c;d;e;f;g] println (data.mkstring ("[", ";", "]");
    Format output string, execution result: a b c d E F g println (Data.mkstring (""));
    
    No output in any format, execution result: ABCDEFG println (data.mkstring); The result of the data operation is assigned to the buffer object, and the result is executed: (A;;; b;; c;; D;; e;; f;;
    g) c val buffer = new StringBuilder ();
    data.addstring (Buffer, "(", ";;", "));
    
    println (buffer);
    The list and array convert the Val array =data println (Array.toarray) to each other;
    
    println (array.tolist); The elements in the copy data object into the NewArray array, where copy to 3 is located after Val newarray = new Array[char] (a) Data.copytoarray (newarray,3)//  Execution Result: ABCDEFG newarray.foreach (PRINT) * * Can be passed through the iterator collection. Next gets the array * A * b/Val
 iterator = Data.toiterator println (Iterator.next ()) println (Iterator.next ())
2 List Common functions


2.1 List function operation (i)

The map, Flatmap, foreach, filter functions of the list are manipulated.

    The elements in the list * 2 operations, Execution results: List (2, 4, 6, 8,) println (list (1,2,3,4,5,6). Map (_*2)) Val data = List ("Sca La "," Hadoop "," Spark ")//get the length of each element, execution results: List (5, 6, 5) println (Data.map (_.length ()))//Convert to list content to reverse, Execution results: List (Alacs, Poodah, Kraps) println (Data.map (_.tolist.reverse.mkstring))//convert each element in the element to a list, execution results: list (Lis
     
    T (S, C, a, L, a), list (H, A, D, O, O, p), list (S, p, a, r, K)) println (Data.map (_.tolist)); 
     Divides the list element into multiple list elements, and then synthesizes the new list element, executing the result: println (Data.flatmap (_.tolist))/* 1 to 9 does not contain 10, execution result: * 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))/println (List.range (1). Flatmap (i => list.range ( 1, i). Map (J => (I,J)))//List elements, 1 to 5 Plus, execution result: sum=15 var sum = 0;
    List (1,2,3,4,5). foreach (Sum+=_); println ("sum=" +sum)//Generate element List, from 1 to 10, does not contain 11, an even number, execution results: List (2, 4, 6, 8, ten) println (List.range (1, one). Filter
    {x => x 2 = 0}); The element println (Data.filter {str => str.length () ==5}) with a data element length of 5)  
2.2 List function operation (ii)

List of partition, find, TakeWhile, Dropwhile, span, forall, exsists function operations.

    
     * * Partition partition
     *
    //////////////////////////////////////////////////////////
    Partition (_%2 = = 0))
    
    //Return option, returns the first conforming value and returns none
    println (List (1,2,3,4,5,6). Find {x => x%2 = 0}) 
  
   println (1,2,3,4,5). Find {x => x <= 0})
    
    ///The element value less than 4 is obtained by the condition and returned to the list, execution result: List (1, 2, 3)
    println (list ( 1,2,3,4,5). TakeWhile (_<4));
    
    Maximum cut off the eligible value
    println (List (1,2,3,4,5). dropwhile {x => x <4})
    
    ///Meet part of the condition, the non-conforming part, the execution result: (List (1, 2 , 3), List (4, 5))
    println (List (1,2,3,4,5). span {x => x < 4})
    
    def hastotallyzerorow (M:list[list[int]) =< c15/>m.exists{
          //ForAll: Returns True if the element is equal to 0, otherwise returns false
          row => row forall{x => x = = 0
      }
    
    val m = L IST (list (1,0,0), List (0,1,0), List (0,0,0))
    println (Hastotallyzerorow (m));

  
2.3 List function operation (iii)

The Foldleft, Foldright, sort function operations of the list.

    def main (args:array[string]): unit = {     //Foldleft initial value is: 0, add from 1 to 100,
Results: 5050       println ((1.to). Foldleft (0) (_ + _));        //The initial value is: 0,1-100 the collection of elements, using the added function as the parameter pass to add      
println ((0/: (1 to (100))) (_ + _));        //The initial value is: 100, each time subtract, the calculation process, (((5-100)), implementation results: -97    
   println ((1.to (5)). Foldright (100) (_-_));       println (((1.to (5)): \ (_-_))        /             *  Platoon Preface              *  Execution results: List ( -3, 1, 2, 4, 6, 8)      &nbsp ;         *  List (8, 6, 4, 2, 1,-3)           &nbsp ;  * *       println (List (1, 2,-3, 4, 6, 8). Sortwith (_ < _));
      println (List (1, 2, -3, 4, 6, 8). Sortwith (_ > _));    }
2.4 List function operation (iv)

Listbuffer, Arraybuffer, Queue, stack function operations.

  def main (args:array[string]): unit = {Import Scala.collection.mutable.ListBuffer;
    Val listbuffer = new Listbuffer[int] ();
    Append element Listbuffer + 1;
    Listbuffer + 2;
    
    Implementation results: Listbuffer (1, 2) println (Listbuffer);
    Import Scala.collection.mutable.ArrayBuffer;
    Val arraybuffer = new Arraybuffer[int] ();
    Arraybuffer + 1;
    Arraybuffer + 2;
    
    
    Implementation results: Arraybuffer (1, 2) println (Arraybuffer);
    /** * Immutable package in the immutable Queue/import scala.collection.immutable.Queue val empty = Queue[int] ();
    Plus an element, the queue itself is immutable, and each operation generates a new queue Val queue1 = Empty.enqueue (1);
    
    Val queue2 = Queue1.enqueue (List (2,3,4,5))//Execution results: Queue (1, 2, 3, 4, 5) println (queue2); Split the quenue2 into two parts: the first element, and the remaining one, consists of the Queue two parts val (element,left) = queue2.dequeue//Execution results: 1:queue (2, 3, 4, 5) Prin
    
    TLN (element + ":" +left); Variable Queue/import Scala.collection.mutable.Queue val in/** * mutable package Queue = scala.collection.mutable.queue[string] ();
    Queue = "a";
    Append List queue ++=list ("B", "C");
    Execution Result: Queue (A, B, c) println (queue); Unlike immutable queue, the variable queue returns only the first element and deletes the first element from the queue, executing the result: a println (Queue.dequeue ())//Execution Result: Queue (b, c) println
    
    
    (queue);
    /** * mutable Package Stack */import Scala.collection.mutable.Stack;
    Val stack = new Stack[int] ();
    Stack.push (1);
    Stack.push (2);
    Stack.push (3);
    Stack.push (10);
    return stack top element: 10, execution Result: println (stack.top);
    Execution results: Stack (3, 2, 1) println (stack);
    Returns the top element of the stack and deletes the top element of the stack, executing the result: println (Stack.pop);
  Execution results: Stack (3, 2, 1) println (stack);
 }

2.5 List Companion object function operation

  def main (args:array[string]): unit = {
    //Generate list object, execution Result: List (1, 2, 3, 4, 5)
    println (list.apply (1, 2, 3, 4, 5)) 
  //generates 1-4list, packets before and after the execution results: List (1, 2, 3, 4)
    println (List.range (1, 5));

    Generate 9-1list, each step is 2, the result: List (9, 7, 5, 3)
    println (List.range (9, 1,-2));

    /
		   * *  zip operation and reverse zip operation, Execution results:
		   * List (  (a,1), (b,2), (c,3), (d,4), (e,5), (f,6))
			 *  (list (A, B, c , D, E, f), List (1, 2, 3, 4, 5, 6))
		   */
    val zipped = "ABCdef". Tolist.zip ("123456789").
    tolist println (zipped) ;
    println (Zipped.unzip)

    //will synthesize a large set of elements in all collections, executing the results: List (A, B, C, D, E, f)
    println (List (' A ', ' B '), List C ', ' d '), List (' e ', ' f ')). Flatten);
    Merges the collection contents, executes the result: List (b, c)
    println (List.concat (list (), list (' B '), List (' C '))
  }



--The above is the list operation Advanced level actual combat content, thanks everybody to my attention.

                                                                                                                                                                                               --Thick and thin hair (YUANXW)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.