scala -- examples of using Iterable sets, Seq sets, Set sets, and Map sets

1. Iterable

1.1 general

Iteratable represents a set that can be iterated. It inherits the Traversable trait and is also the parent trait of other sets. Most importantly, it defines the method to obtain the iterator: def iterator: Iterator[A]. This is an abstract method. Its concrete implementation class needs to implement this method to realize the elements in the iterated return set

1.2 classification

Traversable provides two ways to traverse data:

  • The iterator() method is used to access the function of elements iteratively

    This method belongs to active iteration. We can check whether there are elements through hasNext() and actively call the next() method to obtain elements, that is, we can independently control the iterative process

  • The function of traversing elements is realized by foreach() method

    This method belongs to passive iteration. We only provide one function and cannot control the ergodic process, that is, the iterative process is controlled by the set itself

1.3 case 1: traversing a set

demand

  1. Define a list to store the five numbers 1, 2, 3, 4 and 5
  2. Iterate through the above list through the iterator() method
  3. Traverse the above list through the foreach() method

Reference code

//Case: traversing collection elements
object ClassDemo01 {
  def main(args: Array[String]): Unit = {
    //1. Define a list to store the five numbers 1, 2, 3, 4 and 5
    val list1 = (1 to 5).toList

    //2. Traverse the above list through the iterator() method
    val it: Iterator[Int] = list1.iterator
    while(it.hasNext) {
      val ele = it.next()
      println(ele)
      if(ele == 3) println("Additional operations: " + ele * 10)
    }
    println("-" * 15)

    //3. Traverse the above list through the foreach() method
    list1.foreach(println(_))
  }
}

1.4 case 2: Group traversal

If you encounter the requirement to divide the elements in the Iterable object into fixed size groups and then traverse, you can implement it through the grouped() method

format

def grouped(size: Int): Iterator[Iterable[A]]

demand

  1. Define an iteratable set to store all integers between 1 and 13
  2. Through the grouped() method, the iteratable set is grouped into groups of five elements, traversed and printed

Reference code

//Case: demonstrate the grouped function
object ClassDemo02 {
  def main(args: Array[String]): Unit = {
    //1. Define an iteratable set to store numbers between 1 and 13
    val i1 = (1 to 13).toIterable
    //2. Use the grouped method to group the iteratable set in a group of five elements
    val result1 = i1.grouped(5)
    //3. Traverse elements and print results
    while (result1.hasNext) {
      println(result1.next())
    }
  }
}

1.5 case 3: generating tuples by index

Every element stored in the iteratable collection has an index. If we want to generate a new collection in the format of element - > index, we need to use the zipWithIndex() method

demand

  1. Define an iteratable set to store the five strings "A", "B", "C", "D", "E"
  2. Through the zipWithIndex() method, a new collection is generated in the format of string - > index
  3. A new set is generated according to the format of index - > string
  4. Print results

Reference code

//Case: generating tuples by index
object ClassDemo03 {
  def main(args: Array[String]): Unit = {
    //1. Define an iteratable set to store the five strings "a", "B", "C", "d" and "e"
    val i1 = Iterable("A", "B", "C", "D", "E")
    //2. Use the zipWithIndex() method to generate a new collection in the format of string - > index
    val i2 = i1.zipWithIndex    //List((A,0), (B,1), (C,2))
    //3. Generate a new set according to the format of index - > string
    val i3 = i1.zipWithIndex.map(x => x._2 -> x._1)
    //4. Print results
    println(i2)
    println(i3)
  }
}

1.6 case 4: judge whether the sets are the same

Sometimes, we not only want to judge whether the elements in the two sets are all the same, but also require that the iterative order of the elements in the two sets be consistent. At this time, we can implement the requirement through the sameElements() method

That is, the function of the sameElements() method is to judge whether the elements contained in the collection and the iteration order of the elements are consistent

demand

  1. Defines the iteratable set list1, which contains three elements "A", "B" and "C"
  2. Judge whether list1 and iteratable ("A", "B", "C") sets are the same through the sameElements() method
  3. Judge whether list1 and Iterable("A", "C", "B") sets are the same through the sameElements() method
  4. Defines the iteratable set list2, which contains four elements "A", "B", "C" and "D"
  5. Judge whether list1 and list2 are the same through the sameElements() method

Reference code

import scala.collection.mutable

//Case: check whether two Iterable contain the same element
object ClassDemo04 {
  def main(args: Array[String]): Unit = {
    //1. Define Iterable set i1, including three elements "a", "B" and "C"
    val i1 = Iterable("A", "B", "C")
    //2. Judge whether i1 and Iterable("A", "B", "C") sets are the same
    println(i1.sameElements(Iterable("A", "B", "C")))
    //3. Judge whether i1 and Iterable("A", "C", "B") sets are the same
    println(i1.sameElements(Iterable("A", "C", "B")))
    //4. Define Iterable set i2, including four elements "a", "B", "C" and "d"
    val i2 = Iterable("A", "B", "C", "D")
    //5. Judge whether i1 and i2 are the same
    println(i1.sameElements(i2))

    //6. Extension: create HashSet set to store 1 and 2, create TreeSet set to store 2 and 1, and then judge whether they are the same
    val hs = mutable.HashSet(1, 2)
    val ts = mutable.TreeSet(2, 1)
    println(hs.sameElements(ts))    //The result is true because TreeSet sorts the elements
  }
}

2. Seq

2.1 general

Seq trait represents the sequence of elements arranged in a certain order. Sequence is a special iterative set. Its elements are characterized by order (consistent element access order), repeatability and index

2.2 classification

The inheritance relationship is as follows:

IndexedSeq and LinearSeq are the sub characteristics of Seq, representing the two sub sects of the sequence

  1. IndexedSeq attribute represents index sequence. Compared with Seq, it does not add additional methods. It is more effective for random access to elements. Commonly used subsets include NumericRange, Range, Vector, String, etc

    • Range collection

      Range represents an ordered integer queue with the same interval between each element. For example, odd queue: 1, 3, 5, 7, 9, but Fibonacci sequence 1, 1, 2, 3, 5, 8 does not belong to range class. In short, range is similar to arithmetic sequence in mathematics

    • NumericRange collection

      NumericRange set is a more general arithmetic queue, which can generate Int, BigInteger, Short, Byte and other types of sequences

    • Vector set

      Vector is a universal and immutable data structure. Relatively speaking, it takes a little longer to obtain data, but updating data randomly is much faster than array and linked list

  2. The LinearSeq trait represents a linear sequence. It is implemented through a linked list, so its head, tail and isempty are relatively more efficient. Commonly used subsets include: List, Stack, Queue, etc

    • Stack: represents the stack data structure. The element feature is first in and last out

      Due to historical reasons, Scala's current library also contains an immutable.Stack, but it has been marked as abandoned, because its design is not elegant and its performance is not very good. Because the stack involves the entry and exit of a large number of elements, the application scenario of immutable stack is relatively small, and the most commonly used is variable stack, such as mutable.Stack, mutable.ArrayStack

      • mutable.Stack: it is realized through List, that is, linked List. It is fast in addition and deletion and slow in query
      • mutable.ArrayStack: it is implemented through Array, that is, Array. It is fast to query and slow to add or delete
    • Queue: represents the queue data structure. The element is characterized by first in first out

2.3 case 1: create Seq set

demand

Create a Seq set, store elements 1, 2, 3, 4, 5, and print the results

Reference code

//Case: create Seq object
object ClassDemo01 {
  def main(args: Array[String]): Unit = {
    //1. Create a Seq set to store elements 1, 2, 3, 4, 5
    val s1 = (1 to 5).toSeq
    //2. Print results
    println(s1)
  }
}

2.4 case 2: obtaining length and elements

Because each element of the Seq set has an index, we can get its corresponding element directly through the index, and we can get the length of the set through the length() or size() method

demand

  1. Create a Seq set to store elements 1, 2, 3, 4, 5
  2. Print the length of the set
  3. Gets the element with index 2

Reference code

//Case: get length and element
object ClassDemo02 {
  def main(args: Array[String]): Unit = {
    //1. Create a Seq set to store elements 1, 2, 3, 4, 5
    val s1 = (1 to 5).toSeq
    //2. Print the length of the set
    println(s1.length, s1.size)
    println("-" * 15)

    //3. Get the element with index 2
    println(s1(2))
    println(s1.apply(2))
  }
}

2.5 case 3: get the index value of the specified element

format

To obtain the index value of the specified element, we can use the indexOf(), lastIndexOf(), indexWhere(), lastIndexWhere(),indexOfSlice() method. The specific functions are as follows:

  • indexOf: gets the first occurrence position of the specified element in the list
  • lastIndexOf: gets the position of the last occurrence of the specified element in the list
  • indexWhere: get the index of the element that meets the condition for the first time in the collection
  • lastIndexWhere: get the index of the element that meets the condition and the last occurrence in the collection
  • indexOfSlice: gets the first occurrence position of the specified subsequence in the collection

Note: the above methods are to return the corresponding index after finding the specified data. If the data is not found, return - 1

demand

  1. Define Seq set and store data: 1, 2, 4, 6, 4, 3, 2
  2. Get the index of the first occurrence of element 2 in the collection and print it
  3. Get the index of the last occurrence of element 2 in the collection and print it
  4. Get the index of the first even number less than 5 in the collection and print it
  5. Find the first even index less than 5 in the set from index 2 and print it
  6. Get the last even index less than 5 in the collection and print it
  7. Get the index of subsequence Seq(1, 2) in t1 set for the first time, and print it
  8. Start from index 3, find the index of the subsequence Seq(1, 2) in t1 set for the first time, and print it

Reference code

//Case: get the index value of the specified element
object ClassDemo03 {
  def main(args: Array[String]): Unit = {
    //1. Define Seq set and store data: 1, 2, 4, 6, 4, 3, 2
    val s1 = Seq(1, 2, 4, 6, 4, 3, 2)
    //2. Get the index of the first occurrence of element 2 in the set and print it
    println(s1.indexOf(2))
    //3. Get the index of the last occurrence of element 2 in the set and print it
    println(s1.lastIndexOf(2))
    println("-" * 15)

    //4. Get the index of the first even number less than 5 in the set and print it
    println(s1.indexWhere(x => (x % 2 == 0) && x < 5))
    //5. Start from index 2 to find the first even index less than 5 in the set and print it
    println(s1.indexWhere(x => (x % 2 == 0) && x < 5, 2))
    //6. Get the last even index less than 5 in the set and print it
    println(s1.lastIndexWhere(x => (x % 2 == 0) && x < 5))
     //7. Obtain the index of subsequence Seq(1, 2) in t1 set for the first time, and print it
    println(s1.indexOfSlice(Seq(1, 2)))
    //8. Start from index 3, find the index of the subsequence Seq(1, 2) in t1 set for the first time, and print it
    println(s1.indexOfSlice(Seq(1,2), 3))
  }
}

2.6 case 4: judge whether the specified data is included

If we want to judge whether the sequence starts or ends with the specified data and whether the sequence contains the specified data, we can use startsWith(), endsWith(), contains(), containsSlice(), as follows:

  • startsWith: determines whether the collection starts with the specified subsequence
  • endsWith: determines whether the collection ends with the specified subsequence
  • Contains: determines whether the collection contains a specified data
  • containsSlice: determines whether the collection contains a specified subsequence

demand

  1. The Seq set s1 is defined to store ten data from 1 to 10
  2. Judge whether s1 set starts with subsequence (1, 2) and print the result
  3. Judge whether s1 set starts with subsequence (1, 3) and print the result
  4. Judge whether s1 set ends with subsequence (9, 10) and print the result
  5. Judge whether s1 set ends with subsequence (8, 9) and print the result
  6. Judge whether the s1 set contains element 3 and print the result
  7. Judge whether s1 set contains subsequence Seq(1, 2) and print the result
  8. Judge whether s1 set contains subsequence Seq(1, 3) and print the result

Reference code

//Case: judge whether the set contains specified data
object ClassDemo04 {
  def main(args: Array[String]): Unit = {
    //1. Define Seq set s1 to store ten data from 1 to 10
    val s1 = (1 to 10).toSeq
    //2. Judge whether s1 set starts with subsequence (1, 2) and print the result
    println(s1.startsWith(Seq(1,2)))
    //3. Judge whether s1 set starts with subsequence (1, 3) and print the result
    println(s1.startsWith(Seq(1,3)))
    //4. Judge whether s1 set ends with subsequence (9, 10) and print the result
    println(s1.endsWith(Seq(9,10)))
    //5. Judge whether s1 set ends with subsequence (8, 9) and print the result
    println(s1.endsWith(Seq(8,9)))
    println("-" * 15)
    //6. Determine whether the s1 set contains element 3 and print the result
    println(s1.contains(3))
    //7. Judge whether s1 set contains subsequence Seq(1, 2) and print the result
    println(s1.containsSlice(Seq(1, 2)))
    //8. Judge whether s1 set contains subsequence Seq(1, 3) and print the result
    println(s1.containsSlice(Seq(1, 3)))
  }
}

2.7 case 5: modify the specified element

If we want to modify the value of an element or replace an element in the collection with a specified subsequence, we can use the updated() patch() method, as follows:

  • updated: modifies the element at the specified index position to the specified value

  • patch: modify the element of the specified interval to the specified value

demand

  1. The Seq set s1 is defined to store the five data from 1 to 5
  2. Modify the element value at index 2 as: 10, and print the result
  3. Starting from index 1, replace 3 elements with subsequence Seq(10, 20) and print the results

Reference code

//Case: modifying a specified element
object ClassDemo05 {
  def main(args: Array[String]): Unit = {
    //1. Define Seq set s1 to store five data from 1 to 5
    val s1 = (1 to 5).toSeq
    //2. Modify the element value at index 2 to: 10, and print the result
    val s2 = s1.updated(2, 10)
    println(s2)
    //3. Starting from index 1, replace 3 elements with subsequence Seq(10, 20) and print the results
    val s3 = s1.patch(1, Seq(10, 20), 3)
    println(s3)
  }
}

3. Stack

3.1 general

It represents the stack data structure, and the elements are first in and last out. Due to historical reasons, Scala's current library also contains an immutable.Stack, but it has been marked as abandoned, because its design is not elegant and its performance is not very good. Because the stack involves the entry and exit of a large number of elements, the application scenario of the immutable stack is still relatively small, and the most commonly used is the variable stack, For example: mutable.Stack, mutable.ArrayStack

3.2 diagram

Add elements 1, 2 and 3 to the stack, as shown below:

3.3 common methods

  • Top: gets the top element of the stack, but it will not be removed from the top of the stack
  • push: indicates the stack operation, which is equivalent to pushing elements into the top of the stack
  • pop: remove the stack top element and return this element
  • clear: remove all elements in the collection

be careful:

  1. There is a unique method pushAll() in the immutable.Stack collection to push multiple elements onto the stack
  2. The unique methods of mutable.ArrayStack collection are:
    • Dup (short for duplicate): it can be used to copy top stack elements
    • preserving: this method will execute an expression and recover the stack after the expression is executed, that is, the content of the stack is consistent with that before the call

3.4 example 1: demonstrate Stack variable Stack

demand

  1. Define variable Stack stack and store 5 numbers from 1 to 5
  2. Get the stack top element through the top() method and print it
  3. Add element 6 to the top of the stack through the push() method and print it
  4. Add Seq(11, 22, 33) sequence to the top of the stack through pushAll() and print it
  5. Remove the top element of the stack by pop() method and print it
  6. Remove all elements in the collection through the clear() method

Reference code

import scala.collection.mutable

//Case: demonstrate Stack variable Stack
object ClassDemo06 {
  def main(args: Array[String]): Unit = {
    //1. Define variable Stack and store 5 numbers from 1 to 5
    val s1 = mutable.Stack(1, 2, 3, 4, 5)
    //2. Get the top element of the stack through the top() method and print it
    println(s1.top)
    println(s1.size)
    println("-" * 15)
    //3. Add element 6 to the top of the stack through the push() method and print it
    s1.push(6)
    println(s1)
    println("-" * 15)
    //4. Add Seq(11, 22, 33) sequence to the top of the stack through pushAll() and print it
    s1.pushAll(Seq(11, 22, 33))
    println(s1)
    println("-" * 15)
    //5. Remove the stack top element through the top() method and print it
    println(s1.pop())
    println(s1.size)
    //6. Remove all elements in the collection through the clear() method
    s1.clear()
    println(s1)
  }
}

3.5 case 2: demonstrate ArrayStack variable stack

demand

  1. Define variable stack ArrayStack to store 5 numbers from 1 to 5
  2. Copy the stack top element through the dup() method and print the result
  3. Through the preserving() method, the set elements are cleared first, and then the cleared data in the set is recovered and printed

Reference code

import scala.collection.mutable

//Case: demonstrate ArrayStack variable stack
object ClassDemo07 {
  def main(args: Array[String]): Unit = {
    //1. Define variable stack ArrayStack and store 5 numbers from 1 to 5
    val s1 = mutable.ArrayStack(1, 2, 3, 4, 5)
    //2. Copy the stack top element through dup() method and print the result
    s1.dup()
    println(s1)
    println("-" * 15)
    //3. Use the preserving() method to clear the set elements first, then recover the cleared data in the set, and print
    s1.preserving({s1.clear(); println("Look, did I do it!")})
    println(s1)
  }
}

4. Queue

4.1 General

Represents a queue. The element is characterized by first in first out. Our commonly used queue is a variable queue: mutable.Queue, which is internally implemented by MutableList data structure

4.2 illustration

Add elements 1, 2 and 3 to the queue, as shown below:

4.3 common methods

  • Enqueue: enqueue method, which can pass in zero to multiple elements
  • dequeue: out of the queue, remove an element
  • dequeueAll: removes all elements that meet the criteria
  • dequeueFirst: remove the first element that meets the condition

4.4 case demonstration

demand

  1. Define a variable Queue to store the five data from 1 to 5
  2. Add element 6 to the queue and print
  3. Add elements 7, 8, 9 to the queue and print
  4. Removes the first element of the queue and prints it
  5. Removes the first odd number from the queue and prints the element
  6. Remove all even numbers from the queue and print all removed data
  7. Print the variable Queue to view the final result

Reference code

import scala.collection.mutable

//Case: demonstrate the Queue sequence
object ClassDemo08 {
  def main(args: Array[String]): Unit = {
    //1. Define the variable Queue to store the five data from 1 to 5
    val q1 = mutable.Queue(1, 2, 3, 4, 5)
    //2. Add element 6 to the queue and print
    q1.enqueue(6)
    //3. Add elements 7, 8, 9 to the queue and print
    q1.enqueue(7, 8, 9)
    println(q1)
    println("-" * 15)
    //4. Remove the first element of the queue and print it
    println(q1.dequeue())
    //5. Remove the first odd number of the queue and print the element
    println(q1.dequeueFirst(_ % 2 != 0))
    //6. Remove all even numbers in the queue and print all removed data
    println( q1.dequeueAll(_ % 2 == 0))
    //7. Print the variable Queue and view the final result
    println(q1)
  }
}

5. Set

5.1 general

The elements in the Set set do not contain duplicate elements. The common subclasses are sortedset (the subclass is TreeSet), HashSet and listset

5.2 classification

The inheritance relationship is as follows:

  • HashSet: is implemented in the form of prefix tree (also known as dictionary tree). The elements are unique and unordered, and are often used for statistics
  • LinkedHashSet: elements are unique and orderly
  • TreeSet: elements are unique and sorted

5.3 example

demand

  1. Create a SortedSet set, store elements 1, 4, 3, 2, 5, and print the set
  2. Create a HashSet set, store elements 1, 4, 3, 2, 5, and print the set
  3. Create a LinkedHashSet set, store elements 1, 4, 3, 2, 5, and print the set

Reference code

import scala.collection.{SortedSet, mutable}

//Case: demo Set
object ClassDemo09 {
  def main(args: Array[String]): Unit = {
    //1. Create SortedSet set, store elements 1, 4, 3, 2, 5, and print the set
    val s1 = SortedSet(1, 4, 3, 2, 5)
    println(s1)
    println("-" * 15)
    //2. Create a HashSet set, store elements 1, 4, 3, 2, 5, and print the set
    val s2 = mutable.HashSet(1, 4, 3, 2, 5)
    println(s2)
    println("-" * 15)
    //3. Create a LinkedHashSet set, store elements 1, 4, 3, 2, 5, and print the set
    val s3 = mutable.LinkedHashSet(1, 4, 3, 2, 5)
    println(s3)
  }
}

6. Map

6.1 general

Map represents a map. It is a Set containing key value pairs. The basic operation of map type is similar to that of Set set. Because the element Entry it contains is a key value pair, map provides some methods for key or value operations alone

6.2 classification

The inheritance relationship is as follows:

6.3 examples

demand

  1. Define the Map set and store the data as: "A" - > 1, "B" - > 2, "C" - > 3

  2. Traverse the Map collection

  3. Through the filterKeys() method, obtain the set of key value pair objects with key "B" and print the results

    filterKeys: filter the keys, and get the key values that meet the conditions according to the keys

Reference code

//Case: demonstrate the Map collection
object ClassDemo10 {
  def main(args: Array[String]): Unit = {
    //1. Define the Map set and store the data as: "a" - > 1, "B" - > 2, "C" - > 3
    val m1 = Map("A" -> 1, "B" -> 2, "C" -> 3)
    //2. Traverse the Map set
    m1.foreach(println(_))
    println("-" * 15)
    //3. Obtain the set of key value pair objects with key "B" through the filterKeys() method, and print the results
    println(m1.filterKeys(_ == "B"))
  }
}

7. Case: count the number of characters

7.1 requirements

  1. Prompt the user to enter a string and receive it
  2. Count the number of occurrences of each character in the above string and print the results to the console

7.2 purpose

Comprehensively investigate the collection and enter relevant knowledge points with the keyboard

7.3 steps

  1. Prompt the user to enter a string and receive it
  2. Defines a Map set, which is used to store characters and their occurrences. Key: characters, value: character occurrences
  3. Converts a string into a character array
  4. Traverse the character array to get each character
  5. If the character appears for the first time, record its times as 1. If the character appears repeatedly, add its times + 1, and then store it again
  6. Traverse the collection to see the results

7.4 reference code

import scala.collection.mutable
import scala.io.StdIn

//Case: count the number of characters
object ClassDemo11 {
  def main(args: Array[String]): Unit = {
    //1. Prompt the user to enter a string and receive it
    println("Please enter a string: ")
    val s = StdIn.readLine()
    //2. Define a Map set to store characters and their occurrence times. Key: character, value: character occurrence times
    val m1 = mutable.Map[Char,Int]()
    //3. Convert string to character array
    val chs = s.toCharArray
    //4. Traverse the character array to get each character
    for(k <- chs) {
      //5. If the character appears for the first time, record its times as 1. If the character appears repeatedly, add its times + 1, and then store it again
      m1 += (k -> (if(m1.contains(k)) m1.getOrElse(k, 1) + 1 else 1))
    }
    //6. Traverse the collection and view the results
    for((k, v) <- m1) {
      println(k, v)
    }
  }
}

Tags: Scala Big Data Back-end

Posted on Mon, 06 Dec 2021 00:01:17 -0500 by lorddraco98