Learn scala-. Fourth Chapter mapping and tuples

Source: Internet
Author: User

Knowledge Points:

1. Construct a map, which is a set of dual

// Immutable Mappings // val scores1 = Map (("Alice",), ("Bob",), ("Cindy",)) // Variable Mappings // constructs an empty map New Scala.collection.mutable.hashmap[string,int]

2. Get the values in the map

// throws an exception if it is not included if Else 0= scores1.getorelse ("Bob", 0)

3. Update mappings, Iteration mappings

In a mutable map, you can update the value of a map, or add a new mapping relationship by using the () to the left of the = sign

//Variable MappingsScores2 ("Bob") = 9Scores2 ("Fred") = 8Scores2+ = ("Bob"-9, "Fred"-8) Scores2-= "Alice"//Immutable MappingsVal newscores = scores1 + ("Bob", 9, "Fred", 8)//updated new mappings to save the results as new values//update var variablevar varscores = Map ("Alice", "Bob", 7, "Cindy", "9")) Varscores= Varscores + ("Bob", 9, "Fred", 8) Varscores= Varscores-"Alice"//Iterative Mapping for((k,v) <-scores1)//Handling K,vScores1.keyset//get a collection similar to set ("A", "B", "C") for(v <-scores1.values) println (v)//The values method returns a iterable that can be used in a for loop for((k,v) <-scores1) yield (v,k)//Invert a map

4. Sorted Mappings

An immutable tree map is obtained as follows:

Val scores4 = Scala.collection.immutable.SortedMap ("Alice", "Bob", 7, "Cindy", 9)

For variable tree mappings, the closest option is to use Java's treemap.

If all keys are accessed in the order in which they are inserted, Linkedhashmap is used.

Val months = Scala.collection.mutable.LinkedHashMap ("January", 1, "February", "2", "March", 3, "April", 4, 5,...)

5. Interoperability with Java

Translating Java mappings into a Scala map to use the more convenient Scala mapping API is useful for manipulating variable tree mappings that are not available in Scala.

ImportScala.collection.JavaConversions.mapAsScalaMap//Specify the Scala mapping typeVal Scores:scala.collection.mutable.map[string,int] =NewJava.util.treemap[string,int]//Java.util.properties->map[string,string]ImportScala.collection.JavaConversions.propertiesAsScalaMapval Props:scala.collection.map[string,string]=system.getproperties ()//Scala maps passed to the expected Java mapping methodImportScala.collection.JavaConversions.mapAsJavaMapImportJava.awt.font.textattribute._//The key that will be used to introduce the following mappingVal attrs = Map (FAMILY, "Serif", SIZE, 12)//Scala MappingVal Font =NewJava.awt.Font (Attrs)//the method expects a Java mapping

6. Tuples

A map is a set of key/value duality, and duality is the simplest form of a tuple--tuples are aggregates of different types of values

The value of a tuple is formed by enclosing a single value in parentheses. Using _1, _2, and _3 to access their tuples, the tuple's tuples start at 1.

val = (1,3.14, "Fred")

val second = t._2//second set to 3.14

Also val second = t _2

7. Zipper operation

Val symbols = Array ("<", "-", ">"= Array (2,10,2= Symbols.zip (counts) Pairs.tomap    // zipper operation combined into a map

Practice: (Refer to the original URL of the answer)

1. Set a map that contains some of the equipment you want, along with their price. Then build another map with the same set of keys, but the price hits 90 percent.

scala> val Price = Map ("ipad", "4000", "iphone"--6000, "IWatch", "4000", "ipad", "iphone" ->6000, IWatch) Scalafor ((k,v) <-price) yield (k, v * 0.9= Map (ipad-360 0.0, 5400.0, IWatch, 2700.0)

2. Write a program to read the word from the file. Use a mutable map to count how often each word appears. Reading these words can be done using Java.util.Scanner:
Val in = new Java.util.Scanner (New Java.io.File ("MyFile.txt")) while (In.hasnext ()) handles In.next () or turns to the 9th chapter to see a more scala approach. Finally, print out all the words and the number of times they appear.

Import Scala.io.Source Import Scala.collection.mutable.HashMapobject pract {   def main (args:array[string])  = {      = Source.fromfile ("file.txt"). mkstring      = Source.split ("\\s+")      new  Hashmap[string,int]            for (key <- tokens) {        = map.getorelse (key, 0) +1       }      println (Map.mkstring (","))         }}

3. Repeat the previous exercise, this time with an immutable mapping

The difference between immutable mappings and mutable mappings is that a new mapping is returned each time a new element is added.

Import Scala.io.Sourceobject pract {   def main (args:array[string])  = {      = Source.fromfile (" File.txt "). mkstring      = Source.split (" \\s+ ")      // Note the Var            used here  for (Key <- tokens) {          + = (Key---(Map.getorelse (key, 0) + 1)      }      println (map.mkstring ( /c16> ","))         }}

4. Repeat the previous exercise, this time using sorted mappings so that the words can be printed sequentially

Import Scala.io.Source Import Scala.collection.SortedMapobject pract {   def main (args:array[string])  = {      = Source.fromfile ("file.txt"). mkstring      = Source.split ("\\s+")      //  Note the Var used here for            (key <- tokens) {          + = (Key---(Sortedmap.getorelse (key, 0) + 1 )       }      println (sortedmap.mkstring (",")          }}}

5. Repeat the previous exercise, this time using JAVA.UTIL.TREEMAP and making it suitable for the Scala API

ImportScala.io.SourceImportScala.collection.mutable.MapImportScala.collection.JavaConversions.mapAsScalaMapImportJava.util.TreeMapobject pract {def main (args:array[string])={val Source= Source.fromfile ("file.txt"). mkstring val Tokens= Source.split ("\\s+") Val Map:map[string,int]=NewTreemap[string,int] for(Key <-tokens) {Map (key)= Map.getorelse (key, 0) + 1} println (Map.mkstring (","))      }}

6. Define a chain hash map, map "Monday" to Java.util.Calendar.MONDAY, and then add other dates in turn. Presentation elements are accessed in the order in which they are inserted

ImportScala.collection.mutable.LinkedHashMapImportJava.util.Calendarobject pract {def main (args:array[string])={val Map=Newlinkedhashmap[string, Int] Map+ = ("MONDAY"calendar.monday) Map+ = ("Tuesday"calendar.tuesday) Map+ = ("Wendsday"calendar.wednesday) Map+ = ("Thursday"calendar.thursday) Map+ = ("FRIDAY"calendar.friday) Map+ = ("SATURDAY"calendar.saturday) Map+ = ("SUNDAY"calendar.sunday) println (map.mkstring (","))      }}

7. Print out a table of all Java System Properties

Use of Java System Properties to Scala map

 import   Scala.collection.JavaConversions.propertiesAsScalaMap  import   Scala.collection.Mapobject pract {def main (args:array[string])  = {val Props:map[string,string]  = system.getproperties val Keys = Props.keyset val keylength  = for  (Key &L T;- keys) yield key.length val maxlength  = keylength         . Max  for  (Key <- keys) {print (key) Print ( "* (maxlength- Key.length)) Print ( | ") println (props (key))}}}  

8. Write a function Minmax (Values:array[int]) to return the duality of the minimum and maximum values in the array

def Minmax (Values:array[int])  = {     (values.max,values.min)   }

9. Write a function iteqgt (Values:array[int],v:int) that returns the number of less than V, equal to V, and greater than V in the array, requiring three values to be returned together

def iteqgt (values:array[int],v:int) = {     var a,b,c=0 for     (value <- values) {        if (Value > V) A + = 1       elseif(value = = v) b + = 1       else c + = 1     }     (A , b,c)   }      = {     > V), values.count (_ = = v), Values.count (_ < v)   }

10. When you zip two strings together, such as "Hello". Zip ("world"), what will be the result? Come up with a well-spoken use case

Scala> "Hello". zip ("world"= Vector ((h,w), (E,o), (L,r) , (l,l), (o,d))

Learn scala-. Fourth Chapter mapping and tuples

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.