How to use the mapping map of Scala's various collections (6)

Source: Internet
Author: User
Tags iterable map class sca
1. Create a map

1) Create immutable mappings

scala> val status = Map (1, "a", 2, "B") status:scala.collection.immutable.map[int,string] = map (1, A, 2- > B) scala> val status = Map ((1, "a"), (2, "B")) status:scala.collection.immutable.map[int,string] = map (1, A, 2-& Gt b

2) Create a mutable mapping either by importing it into the scope or by specifying the full path to the Scala.collection.mutable.Map class when the instance is created.

scala> var status = Collection.mutable.Map ((1, "a"), (2, "B")) status:scala.collection.mutable.map[int,string] = Map ( 2, B, 1, a)

3) Create an empty variable map at the time of creation, and then add the element.

scala> var status = collection.mutable.map[int,string] () status:scala.collection.mutable.map[int,string] = Map () Scala> Status + = ((1, "a")) res38:scala.collection.mutable.map[int,string] = Map (1-a) scala> status + = ((3, "C") , (2, "B")) res39:scala.collection.mutable.map[int,string] = Map (2, B, 1, A, 3, c)
2.Map use of the scene

1) If you want to return elements in an ordered map, use SortedMap.

Scala> Import Scala.collection.SortedMapimport scala.collection.sortedmapscala> val grades = SortedMap ("Kim", ("Al", "("), ("Mes", "("), ("EMA", +), ("Han", "grades:scala.collection.sortedmap[string,int")) = Map (Al--, EMA ----, Han->93, Kim---------scala> val grades = SortedMap ((1,90), (3,86), (2,88), (5,78), (4,93)) Grad Es:scala.collection.sortedmap[int,int] = Map (1, 2, 3, 4, 5, 78)

2) Return elements in the order they were inserted, with only a variable linkedhashmap.

scala> Import Scala.collection.mutable.LinkedHashMapimport scala.collection.mutable.linkedhashmapscala> var Status = Linkedhashmap ((5, "apple")) status:scala.collection.mutable.linkedhashmap[int,string] = Map (Apple, 5) Scala> Status + = ((3, "orange")) res40:scala.collection.mutable.linkedhashmap[int,string] = Map (Apple, 3, 5) Orange) scala> Status + = ((6, "banana")) res41:scala.collection.mutable.linkedhashmap[int,string] = Map (5, Apple , 3->orange, 6-Banana)

3) returns the element in the reverse order of insertion, which can be a variable or immutable listmap.

scala> import Scala.collection.mutable.ListMapimport scala.collection.mutable.listmapscala> var status = Listmap ((1, "a")) status:scala.collection.mutable.listmap[int,string] = Map (1-a) scala> status + = ((1, "a")) Res43:scala.collection.mutable.listmap[int,string] = Map (1-a) scala> status + = ((2, "B")) Res44: Scala.collection.mutable.listmap[int,string] = Map (2, B, 1, a) scala> status + = ((3, "C")) Res45:scala.collect Ion.mutable.listmap[int,string] = Map (3-C, 1-A, 2-B)
3. Add, update, and delete elements of a mutable map

1) Add elements to the variable map by assigning a value to the key.

scala> var status = scala.collection.mutable.map[string,string] () status:scala.collection.mutable.map[string, String] = map () scala> status ("a1") = "A1A" scala> statusres47:scala.collection.mutable.map[string,string] = map ( A1-A1A)

2) Add one or more elements through the + = method.

scala> var status = scala.collection.mutable.map[string,string] () status:scala.collection.mutable.map[string, String] = map () scala> Status + = (("A1", "A1A") Res50:status.type = map (A1-A1A) scala> Statusres51:scala.collec Tion.mutable.map[string,string] = Map (A1-A1A) scala> Status + = (("A1", "A1A"), ("A2", "A2A")) Res52:status.type = Map (A1-A1A, A2-A2A) scala> statusres53:scala.collection.mutable.map[string,string] = map (A1, A1A, A2- > A2A)

3) Add multiple elements from another collection with ++=.

scala> var status = scala.collection.mutable.map[string,string] () status:scala.collection.mutable.map[string, String] = map () scala> status ++= List (("A1", "A1A"), ("A2", "A2A")) Res55:status.type = map (A1, A1A, A2, A2A)

4) Use the-= method to remove one or more elements from the map by specifying the key of the element.

Scala> Status ++= List (("A1", "A1A"), ("A2", "A2A")) Res56:status.type = Map (A1-A1A, A2-A2A) scala> status- = "a1" Res57:status.type = Map (A2-A2A) scala> statusres58:scala.collection.mutable.map[string,string] = map (A2- > A2A) scala> Status-= ("A1", "A2") Res60:status.type = Map () scala> statusres61:scala.collection.mutable.map[ String,string] = Map ()

5) Delete the specified element in the collection with--=.

scala> var status = scala.collection.mutable.map[string,string] () status:scala.collection.mutable.map[string, String] = map () scala> status ++= List (("A1", "A1A"), ("A2", "A2A")) Res67:status.type = map (A1, A1A, A2, A2A) SCA La> status--= List ("A1", "A2") Res68:status.type = Map () scala> statusres69:scala.collection.mutable.map[string, String] = Map ()

6) updates the element by assigning a value to the key of the element.

scala> var status = scala.collection.mutable.map[string,string] () status:scala.collection.mutable.map[string, String] = map () scala> status ++= List (("A1", "A1A"), ("A2", "A2A")) Res72:status.type = map (A1, A1A, A2, A2A) SCA La> status ("a1") = "Hello World" scala> statusres74:scala.collection.mutable.map[string,string] = Map (A1- Hello World, A2-A2A)
4. Add, update, and delete elements for immutable mappings

1) Add one or more elements with a + method and assign the result to a new variable in the process.

scala> val A = Map (("A1", "A1A")) a:scala.collection.immutable.map[string,string] = map (A1-A1A) scala> val B = A + (("A2", "A2A")) b:scala.collection.immutable.map[string,string] = Map (A1, A1A, A2, A2A) scala> val C = B + ( ("A3", "A31"), ("A4", "a4a")) c:scala.collection.immutable.map[string,string] = Map (A1-A1A, A2-A2A, A3-A31 , A4-a4a)

2) updating a key-value pair with an immutable map requires the + method to re-assign the key/value and replace the old value with the new value.

scala> val A = Map (("A1", "A1A")) a:scala.collection.immutable.map[string,string] = map (A1-A1A) scala> val B = A + (("A2", "A2A")) b:scala.collection.immutable.map[string,string] = Map (A1, A1A, A2, A2A) scala> val C = B + ( ("A1", "Hello World")) C:scala.collection.immutable.map[string,string] = Map (A1, Hello World, A2-A2A)

3) Use-method to delete one or more elements.

scala> val A = Map (("A1", "A1A")) a:scala.collection.immutable.map[string,string] = map (A1-A1A) scala> val B = A + (("A2", "A2A"), ("A3", "a3a"), ("A4", "a4a")) b:scala.collection.immutable.map[string,string] = Map (A1-A1A, A2- > A2A, a3-> a3a, A4-a4a) scala> val c = B-"A1"-"A2" c:scala.collection.immutable.map[string,string] = Ma P (A3-a3a, A4-a4a) scala> val d = C-"A4" d:scala.collection.immutable.map[string,string] = Map (A3-a3a )

When an immutable variable is declared as Var, it is still an immutable map and cannot be re-assigned to the elements in the map.

5. Access to mapped values

1) accesses a separate value saved in the map, and throws an exception if the key does not exist. To avoid this problem, you can use the Withdefaultvalue method when you create the map. The method creates a default value, and if the key is not found, the mapping returns the value.

scala> val status = Map ((1, "a"), (2, "B"), (3, "C")). Withdefaultvalue ("Not Found") Status: Scala.collection.immutable.map[int,string] = Map (1, 2, B, 3, C) scala> status (4) res5:string = Not Fou Ndscala> status (3) res6:string = C

2) When searching for a key, you can use the Getorelse method, which returns a default value when the specified key is not found.

scala> val status = Map ((1, "a"), (2, "B"), (3, "C")) status:scala.collection.immutable.map[int,string] = map (1 A, 2 B, 3, c) scala> val s = status.getorelse (6, "not such value") S:string = not such value

3) You can return to the option object using the Get method.

scala> val status = Map ((1, "a"), (2, "B"), (3, "C")) status:scala.collection.immutable.map[int,string] = map (1 A, 2  B, 3, c) scala> val s = status.get (5) s:option[string] = nonescala> val s = status.get (2) s:option[string] = Some (b)
6. Traversal of Mappings

1) The For loop iterates through all the mapping elements.

scala> val status = Map ((1, "a"), (2, "B"), (3, "C"), (4, "D")) status:scala.collection.immutable.map[int,string] = map (1 A, 2, B, 3, C, 4, D) scala> for ((k,v) <-status) println (S "Key: $k, Value: $v") key:1, Value:ak Ey:2, Value:bkey:3, Value:ckey:4, value:d

2) match the expression with the Foreach method.

scala> val status = Map ((1, "a"), (2, "B"), (3, "C"), (4, "D")) status:scala.collection.immutable.map[int,string] = map (1 A, 2, B, 3, C, 4, D) scala> status.foreach{| case (K,V) = println (S "Key: $k, Value: $v") |} Key:1,value:akey:2,value:bkey:3,value:ckey:4,value:d

3) Use the tuple syntax to access the key/value field.

scala> val status = Map ((1, "a"), (2, "B"), (3, "C"), (4, "D")) status:scala.collection.immutable.map[int,string] = map (1 A, 2, B, 3, C, 4, D) scala> status.foreach (x = println (S "Key: ${x._1},value: ${x._2}")) Key:1,v Alue:akey:2,value:bkey:3,value:ckey:4,value:d

4) If you want all the keys in the map, the keys method returns iterable.

scala> val status = Map ((1, "a"), (2, "B"), (3, "C"), (4, "D")) status:scala.collection.immutable.map[int,string] = map (1 A, 2, B, 3, C, 4, D) scala> Status.keys.foreach (key) = println (key) 1234

5) If you want to map all of the values in value, use the values method to traverse all the values in the map.

scala> val status = Map ((1, "a"), (2, "B"), (3, "C"), (4, "D")) status:scala.collection.immutable.map[int,string] = map (1 A, 2, B, 3, C, 4, D) scala> Status.values.foreach ((value) = println (value)) ABCD
7. Value of the action map

1) mapvalues is a good choice if you want to traverse the map and manipulate each value. It can execute a function on each mapped value, and then return the modified map.

scala> var x = Collection.mutable.Map ((1, "a"), (2, "B")) x:scala.collection.mutable.map[int,string] = Map (2, B, 1- > A) scala> val y = x.mapvalues (_.touppercase) y:scala.collection.map[int,string] = Map (2, B, 1, a)

2) The Transform method can use the key/value to implement a transform method at the same time.

scala> val map = map ((1,10), (2,20), (3,30)) Map:scala.collection.immutable.map[int,int] = map (1, 2, 20, 3 scala> val newmap = Map.transform ((k,v) + K + V) newmap:scala.collection.immutable.map[int,int] = map (1-& Gt One, 2, 3, 33)
8. Get all the keys and values from the map

1) Use the Keyset method to get all the keys in a collection.

scala> val status = Map (("A1", "A1A"), ("A2", "A2A"), ("A3", "a3a")) status:scala.collection.immutable.map[string, String] = Map (A1-A1A, A2-A2A, A3-a3a) scala> status.keysetres14:scala.collection.immutable.set[string ] = Set (A1, A2, A3)

2) Use the keys method to obtain a iterable.

scala> status.keysres16:iterable[string] = Set (A1, A2, A3)

3) Use the Keysiterator method to get all keys as iterators.

scala> status.keysiteratorres17:iterator[string] = Non-empty Iterator

4) Use the values method to get all the values in the map and convert the result to a Iterable object.

scala> status.valuesres18:iterable[string] = Maplike (A1A, A2A, a3a)

5) Use the Valuesiterator method to return the iterator object.

scala> status.valuesiteratorres19:iterator[string] = Non-empty Iterator

Both the Keysiterator and Valuesiterator methods return an iterator from the mapped data. These methods do not create a new collection, but simply provide a way to iterate over an existing iterator.

9. Invert key Values

You can use for derivation to invert the key value of the map and assign the result to a new variable. However, in a map, key is not duplicated, and value can be duplicated, but it may lose data when reversed.

scala> val status = Map (("A1", "A1A"), ("A2", "A2A"), ("A3", "a3a")) status:scala.collection.immutable.map[string, String] = Map (A1-A1A, A2-A2A, A3-a3a) scala> val newmap = for ((k,v) <-status) yield (v,k) newmap:s Cala.collection.immutable.map[string,string] = Map (A1A-A1, A2A-A2, a3a-A3)
10. The presence of keys/values in the test map

1) Use the Contains method to test whether the map contains keys.

scala> val status = Map (("A1", "A1A"), ("A2", "A2A"), ("A3", "a3a")) status:scala.collection.immutable.map[string, String] = Map (A1-A1A, A2-A2A, A3-a3a) Scala> if (Status.contains ("A1")) println ("found A1") Else Print ln ("not Found") found a1scala> if (Status.contains ("A5")) println ("found A5") Else println (' not found ') not found

2) Use the Valuesiterator method to search for values, combined with exists and contains.

scala> val status = Map (("A1", "A1A"), ("A2", "A2A"), ("A3", "a3a")) status:scala.collection.immutable.map[string, String] = Map (A1-A1A, A2-A2A, A3-a3a) scala> status.valuesIterator.exists (_.contains ("A2A")) Res22:boo Lean = truescala> status.valuesIterator.exists (_.contains ("a2a2")) Res23:boolean = False
11. Sort the mappings by key or value

1) You can use the SortBy method to sort the mappings from low to high in the value (_2)/Key (_1).

Scala> val grade = Map ((1,98), (2,89), (3,88), (4,93), (5,95)) Grade:scala.collection.immutable.map[int,int] = map (5- >, 1, 98, 2, 3, 4, scala> import Scala.collection.immutable.ListMapimport scala.co Llection.immutable.listmapscala> Listmap (Grade.toSeq.sortBy (_._2): _*) RES25: Scala.collection.immutable.listmap[int,int] = Map (3, 2, 4, 5, 1, 98)

2) the value (_2)/key (_1) can be sorted in ascending or descending order using the Sortwith method.

By value Ascending:scala> listmap (Grade.toSeq.sortWith (_._2 < _._2): _*) Res28:scala.collection.immutable.listmap[int, INT] = Map (3, 2, 4->93, 5, 1, 98)//By value descending:scala> listmap (Grade.toSeq.sortWith (_._2 & Gt _._2): _*) Res29:scala.collection.immutable.listmap[int,int] = Map (1-98, 5-, 4->93, 2-, 3-8 8)

About _*:
Its role is to convert the data and then pass it as multiple parameters to Listmap.

12. Maximum value of the key value in the map

1) sort the keys.

Scala> val grade = Map ((1,98), (2,89), (3,88), (4,93), (5,95)) Grade:scala.collection.immutable.map[int,int] = map (5- >, 1, 98, 2-3, 4, scala> grade.maxres31: (int, int) = (5,95) scala> grade.keysiterator.m Axres32:int = 5scala> grade.keysIterator.reduceLeft (x x > Y) x else y) Res33:int = 5

2) sort the values.

Scala> val grade = Map ((1,98), (2,89), (3,88), (4,93), (5,95)) Grade:scala.collection.immutable.map[int,int] = map (5- >, 1, 98, 2, 89,3, 4, scala> grade.valuesIterator.maxres40:Int = 98scala> Grade.va Luesiterator.reduceleft ((x, y) = if (× > y) x else y) Res41:int = 98scala> Grade.valuesIterator.reduceLeft (_ max _ ) Res42:int = 98

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.