Scala Learning (iv)---mappings and tuples

Source: Internet
Author: User

Mappings and tuples

Summary :

A classic programmer's famous saying is: "If there is only one data structure, then use a hash table." A hash table , or more generally, a mapping , is one of the most flexible data structures. A map is a collection of key/value duality . Scala has a common term: tuples, which are aggregates of N objects, do not necessarily have the same type . duality is simply a n=2 tuple, and tuples are especially useful for those who need to aggregate two or more values together. The main points of this article include:

Scala has a very easy-to-use syntax for creating, querying, and traversing mappings.

02. You need to make choices from mutable and immutable mappings.

03. By default, you get a hash map shot, but you can also indicate that you want to map the tree.

04. You can easily switch back and forth between Scala maps and Java maps.

05. Tuples can be used to aggregate values.

Construct mappings

Immutable mappings

We can construct a mapping like this:

Val scores = Map ("Alice", "Bob"->3, "Cindy"->8)

The code above constructs an immutable map[string,int] whose value cannot be changed .

Variable mappings

If you want a mutable mapping, use the

Val scores = scala.collection.mutable. Map ("Alice", "Bob"->3, "Cindy"->8)

If you want to start with an empty map, you need to select a mapping implementation and give the type parameter :

Val scores = new scala.collection.mutable. HashMap [String, Int]

In Scala, a map is a set of dual. duality is simply a group of two values that are not necessarily of the same type, such as ("Alice", 10)

Operator Creation Dual

Operator is used to create a dual:

"Alice"->10

The values for the above code output are:

("Alice", 10)

Mapping can also be defined in the following way:

Val Scores=map ("Alice", Ten), ("Bob", 3), ("Cindy", 8))

But the operator looks a little more readable than parentheses, and more in line with the intuitive sense of mapping: mapping This data structure is a function of mapping keys to values . The difference is that the usual function calculates the value , and the mapping is just a query .

Get the values in the map

In Scala, the similarity between functions and mappings is particularly noticeable, because you will use () notation to find the value corresponding to a key :

Val Bobsscore = Scores ("Bob")//similar to scores in Java. Get ("Bob")

If the map does not contain the key used in the request, an exception is thrown. To check if there is a specified key in the map , you can use the contains method:

Val Bobsscore = if (Scores.contains ("Bob")) scores ("Bob") ELSE 0

Since such a combination call is common, here's a quick way to do this:

Val Bobsscore = Scores.getorelse ("Bob", 0)//If the map contains the key "Bob", the corresponding value is returned; otherwise, 0

Finally, the map. Get (key) Such a call returns an option object , either some (the key corresponding to the value), or none

Update key values

Updating a mutable map

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

Scores ("Bob") = 10//update Key "Bob" for the corresponding value

Scores ("Fred") =7//Add new key/value dual to scores

Alternatively, you can add multiple relationships with the + = Operation :

scores+= ("Bob", "Fred"->7)

To remove a key and its corresponding value, use the- = operator :

Scores-= "Alice"

Immutable mappings

Although you cannot update an immutable mapping, you can do something equally useful to get a new mapping that contains the required updates:

Val Newscores = scores+ ("Bob"->10, "Fred"->7)//Updated New mappings

The Newscores map contains the same mapping as scores, and "Bob" was updated, and "Fred" was added in

In addition to saving the result as a new value, you can also update the VAR variable:

var scores = ...

Scores = scores+ ("Bob"->10, "Fred"->7)

Similarly, to remove a key from an immutable map, you can use an operator to get a new map that removes the key:

Scores = scores-"Alice"

You may find it inefficient to create new mappings in such a constant manner, but that is not the case. The old and new mappings share most of the structure. This is possible because they are immutable.

Iterative mapping

The following super-simple loop iterates through all the key/value pairs in the map:

For ((k,v) <-mapping) processing K and V

The "Magic" here is that you can use pattern matching in Scala's for loop. In this way, you do not need a miscellaneous method call, you can get each of the dual keys and values

If for some reason you only need access to keys or values , like Java, you can use the keySet and Values methods. The values method returns-a iterable that you can use in the For loop iterable

Scores. KeySet //A collection similar to set ("Bob", "Cindy", "Fred", "Alice")

For (v <-scores. Values) Printlni (v)//will print 10 8 7 10 or other permutation combinations

To invert a map, that is, the position of the swap key and the value, you can use:

For ((k,v) <-mapping) yield (V.K)

Sorted mappings

When you manipulate the map, you need to select an implementation: A hash table or a balance tree . By default, Scala gives you a hash table. Because there are no good hash functions for the keys used, or you need to access all the keys sequentially, you might want a tree-shaped map.

To get an immutable tree map instead of a hash map, you can use:

Val scores = scala.collections.immutable. SortedMap ("Alice"->10, "Fred"->7, "Bob"->3, "Cindy"->8)

Unfortunately, Scala (2.9) does not have a mutable tree-shaped mapping. If that's what you want, the closest option is to use Java's TreeMap. Note that if you want to access all the keys in the order in which they are inserted, use Linkedhashmap, for example:

Val months = scala.collection.mutable. Linkedhashmap ("January", 1, "February", 2, "March", 3, ...)

Interoperability with Java

Java to Scala

If you get a Java mapping through a Java method call , you might want to convert it into a Scala map to use the more convenient Scala mapping API. This is also useful for scenarios where you need to manipulate Scala and do not provide a variable tree mapping. You only need to add the following incoming statements:

Import scala.collection.JavaConversions. Mapasscalamap

The conversion is then triggered by specifying the Scala mapping class type:

Val scores:scala.collection.mutable. Map[string, Int]=new java.util. Treemap[string, Int]

In addition, you can also get conversions from java.util.Properties to map[string,string] :

Import Scala.collection.JavaConversions.propertiesAsScalaMap

Val props: scala.collection.map[string, String] = System.getproperties ()

Scala to Java

Conversely, to pass the Scala mapping to the intended Java mapping method, provide the opposite implicit conversion

For example:

Import Scala.collection.JavaConversions.mapAsjavaMap

Import Java.awt.font.TextAttribute. _//Introduce the key that will be used to map the following

Val attrs = map (FAMILY, "Serif", SIZE--)//Scala map

Val font=new Java.awt.Font (attrs)//The method expects a Java map

Meta-group

Tuple definition

A map is a collection of key/value duality. The simplest form of the dual foot tuple (tuple), which is the aggregation of different types of values . The value of a tuple is formed by enclosing a single value in parentheses. For example:

(1, 3.14, "Fred")

is a tuple that is of type:

Tuple3 [Int, Double, java.lang.String]

Type definitions can also be written as:

(Int, Double, Java,lang.) String)

If you have a tuple, such as:

Val t = (1,3.14, "Fred")

You can use methods _1, _2, _3 to access its elements, such as:

Val second = t._2//Set second to 3.14

It is important to note that the tuple's tuples start at 1 instead of 0, and the positions in the array or string are different. You can write t._2 as T-_2, with spaces instead of periods, but not t_2

Get tuples

Typically, you use pattern matching to get the tuple's elements, for example:

Val (First,second,third) =t//Set first to 1,second to 3.14. Third set as "Fred"

If not all of the components are required, then you can make use of _ at unwanted parts locations :

Val (First, second, _) = t

Tuples can be used in cases where a function needs to return more than one value . For example, Stringops's partition method returns a pair of strings that contain characters that satisfy a condition and do not satisfy the condition:

"New York". Partition (_.isupper)//Output dual ("NY", "ew ork")

Zipper operation

One of the reasons to use tuples is to tie multiple values together so that they can be processed together , which can usually be done in a zip method . For example, the following code:

Val symbols = Array ("<", "-", ">")

Val counts = Array (2, 10, 2)

Val pairs = Symbols.zip (counts)

An array of output duality:

Array ("<", 2), ("-", "Ten"), (">", 2))

These duality can then be processed together:

For ((s,n) <-pairs) Console.print (s*n)//print <<---------->>

It is important to note that the Tomap method allows you to convert a set of dual to a mapping . If you have a collection of keys and a set of values that correspond to them, then you can use a zipper operation to combine them into a single map: Keys.zip (values). Tomap

If you think reading this blog gives you something to gain, you might want to click "recommend" in the lower right corner.
If you want to find my new blog more easily, click on "Follow Me" in the lower left corner.
If you are interested in what my blog is talking about, please keep following my follow-up blog, I am "sunddenly".

This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

Scala Learning (iv)---mappings 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.