Summary of scala collections

I. Overview

This collection is similar to java except that scala is reimplemented according to its syntax
Divided into variable and immutable sets
Common list of collections

  List

Summary
         Stores the same type of sequential storage structure
         Invariant, once defined, cannot be changed
         Nested Definitions
         If you want to use mutability, you need to manually import the package scala.collection.mutable.ListBuffer
Use
-Define list
 

  //Reshaping list
    var nums:List[Int] = List(1,2,3,4)
    //String type list
    var str:List[String] = List("java","python","scala")
    //2-D list
    var dim:List[List[Int]] = List(List(1,2,3),List(4,5,6))
  - Use Nil and::To build list

 

  //Reshaping list
    var nums:List[Int] = 3::2::1::Nil
    //String type list
    var str:List[String] = "scala"::"python"::"java"::Nil
    //2-D list
    var dim:List[List[Int]] = (1::2::3::Nil)::(4::5::6::Nil)::Nil

Common operations
         head returns the first element of the list
         tail returns a list containing elements other than the first
         isEmpty returns true when the list is empty
        ::: Operator or List:: () method or List.concat() method to join two or more lists
         The List.fill() method creates a list of elements with a specified number of repetitions
         The List.tabulate() method creates a list from a given function.
         List.reverse is used to reverse the order of the list
Example:

package com.antg.day03.scala

object TestFunction {
  def main(args: Array[String]): Unit = {
    //Reshaping list
    var nums:List[Int] = 3::2::1::Nil
    //String type list
    var str:List[String] = "scala"::"python"::"java"::Nil
    //2-D list
    var dim:List[List[Int]] = (1::2::3::Nil)::(4::5::6::Nil)::Nil

    //head returns the first element of the list
    println(dim.head)//List(1, 2, 3)
    
    //tail returns a list containing elements other than the first
    println(nums.tail)//List(2, 1)
    
    //isEmpty returns true when the list is empty
    println(nums.isEmpty)//false
    
    //::: Operator or List::: () Method or List.concat() Method to join two or more lists
    var a = nums:::4::Nil
    var b = nums.:::(4::Nil)
    var c = nums.concat(4::Nil)
    println(a)//List(3, 2, 1, 4)
    println(b)//List(4, 3, 2, 1)
    println(c)//List(3, 2, 1, 4)
    
    //The List.fill() method creates a list of elements with a specified number of repetitions
    var d = List.fill(3)("java")
    println(d)//List(java, java, java)
    
    //The List.tabulate() method creates a list from a given function.
    var e = List.tabulate(3)(x=>x+1)
    println(e)//List(1, 2, 3)
    var f = List.tabulate(3,4)((x,y)=>x+y)
    println(f)//List(List(0, 1, 2, 3), List(1, 2, 3, 4), List(2, 3, 4, 5))
    
    //List.reverse is used to reverse the order of the list
    println(nums.reverse)//List(1, 2, 3)
  }
}

3. Set

Summary
         There are no duplicate object collections, the underlying is a hash structure
         Default is immutable
         If you want to change, introduce the package scala.collection.mutable.Set
Use
Invariant Set
 

  var a = Set(1,2,3,2,2,2,2)
    println(a)//1,2,3
    var b = Set(4,5,6)
    var c = a.concat(b)
    println(c)//5,1,6,2,3,4

Variable Set

    var a = Set(1,2,3,2,2,2,2)
    //Add Elements
    a.add(4)
    //Delete element
    a.remove(1)
    println(a)//2,3,4
  • Common operations
    • head returns the first element of the collection
    • tail returns a collection containing elements other than the first element
    • isEmpty returns true when the collection is empty
    • Connect two sets using the **+ ** operator or **Set. ++() ** method
    • Use the Set.min method to find the smallest element in the collection and the Set.max method to find the largest element in the collection
    • Use the Set. &method or Set.intersect method to view the intersection elements of two collections.

Example
 

   var a = Set(1,2,3)
    //head returns the first element of the collection
    println(a.head)//1

    //tail returns a collection containing elements other than the first element
    println(a.tail)//HashSet(2, 3)

    //isEmpty returns true when the collection is empty
    println(a.isEmpty)//false

    //Connect two sets using the ++ operator or Set. +() method
    var b = Set(4,5,6)
    println(a++b)//HashSet(1, 2, 3, 4, 5, 6)

    //Use the Set.min method to find the smallest element in the collection and the Set.max method to find the largest element in the collection
    println(a.min)//1
    println(a.max)//3

    //Use the Set. &method or Set.intersect method to view the intersection elements of two collections.
    var c = Set(2,3,4)
    println(a.&(c))//HashSet(2, 3)

4. Map

  • Summary
    • An iterative key/value pair structure, also known as a hash table
    • All values can be obtained by keys, which are unique
    • Two types, variable and immutable, differ in that a mutable object can modify it, but an immutable object cannot
    • Invariant Map used by default, variable Map requires the **import scala.collection.mutable.Map ** class

Use
 

  //Invariant Map
    var a = Map("a"->1,"b"->2)
    val a1 = Map("a"->1,"b"->2)
    //Add Elements
    a+=("c"->3)
    //A1+=("c"->3) This will cause an error
    println(a)//Map(a -> 1, b -> 2, c -> 3)
    
    //Variable Map
    var b = scala.collection.mutable.Map("a"->1,"b"->2)
    b.put("c",3)
    println(b)//HashMap(a -> 1, b -> 2, c -> 3)
  • Summary of Invariant and Variable Map s
    • Invariant Map
      • api is not very rich
      • If var modifier, variable reference, read and write support
      • If it is a valmodifier, the reference is immutable, it can only write the value once, and then read-only
    • Variable Map
      • The api enrichment is similar to Map in Java
      • If var modifier, variable reference, read and write support
      • If it is a val modifier, the reference is immutable, supporting read and write
    • summary
      • Variable and immutable, primarily through Vals and var s to define intent
      • api richness is different
  • Common operations
    • Keys: Returns all keys of a Map
    • Values: Returns all the values of a Map (value)
    • isEmpty: Returns true when Map is empty
    • Connect two Maps using the **+** operator or **Map. ++()** method, removing duplicate key s when a Map is merged.
    • Output keys and values in Map through a foreach loop
    • Use the **Map.contains ** method to see if the specified Key exists in the Map

Example
 

   var a = Map("a" -> 1, "b" -> 2, "c" -> 2)
    //Keys: Returns all keys of a Map
    println(a.keys) //Set(a, b)

    //Values: Returns all the values of a Map (value)
    println(a.values) //Iterable(1, 2, 2)

    //isEmpty: Returns true when Map is empty
    println(a.isEmpty) //false

    //Connect two Maps using either the ++ operator or the Map. +() method, removing duplicate key s when a Map is merged.
    var b = Map("c" -> 3, "d" -> 4)
    println(a ++ b) //HashMap(a -> 1, b -> 2, c -> 3, d -> 4)

    //Output keys and values in Map through a foreach loop
    a.keys.foreach(x => println(x + "---->" + a.get(x))) //a---->Some(1),b---->Some(2),c---->Some(2)
    a.foreach(x => println(x)) //(a,1),(b,2),(c,2)

    //Use the Map.contains method to see if the specified Key exists in the Map
    println(a.contains("a")) //true

V. Tuples

  • concept
    • Like lists, tuples are immutable
    • Unlike lists, tuples can contain different types of elements
    • Tuples are defined by'()'
    • Access specific elements through. _ Index to access, index starting at 1

Use
   

 //Define tuples directly
    var a = (1,2,3,"java","scala","python")
    println(a)//(1,2,3,java,scala,python)

    //Defining tuples through Tuple
    var b = new Tuple3(1,2,"java")
    println(b)//(1,2,java)

    //Accessing an element
    println(a._1)//1
    println(a._2)//2
    println(a._3)//3

    //ergodic
    a.productIterator.foreach(x=>println(x))

6. Option

  • Summary
    • Represents a container that may or may not contain values. Primarily used to indicate that a value is optional
    • Option[T] is a container of optional values of type T: if the value exists, Option[T] is a Some[T], if it does not exist, Option[T] is an object None.
  • common method
    • The getOrElse() method gets the elements present in the tuple or uses their default values
    • The isEmpty() method detects whether an element in a tuple is None

Example
 

  //Define a map
    var map = Map("java"->1,"scala"->2)

    //The result from the get method is an option
    println(map.get("java"))//Some(1)
    println(map.get("c"))//None

    //The isEmpty() method detects whether an element in a tuple is None
    println(map.get("java").isEmpty)//false

    //The getOrElse() method gets the elements present in the tuple or uses their default values
    println(map.get("scala").getOrElse())//2

7. Iterator

  • Summary
    • Not a collection, it's a way to access a collection
    • The basic operations are hasNext and next
  • Common operations
    • it.hasNext() is used to detect if there are elements in the collection
    • it.next() returns the next element of the iterator and updates the state of the iterator
    • max: Gets the maximum value of the iterator's corresponding set
    • min: Gets the minimum value of the iterator's corresponding set
    • size/length: Gets the length of the iterator's corresponding set

Example
 

   //ergodic
    var a = Iterator("java", "scala", "c++")
    while (a.hasNext) {
      println(a.next())
    }

    //Maximum
    var b = Iterator(1, 2, 3)
    println(b.max)


    //Minimum Value
    var c = Iterator(1, 2, 3)
    println(c.min)

    //Find Length
    var d = Iterator(1, 2, 3)
    println(d.length)

Tags: Scala Back-end

Posted on Sat, 04 Dec 2021 12:32:38 -0500 by bombas79