Exercises
Set up a map of prices for a number of gizmos that you covet. Then produce a second map with the same keys and the prices at a 10 percent discount.
Write a program that reads words from a file. Use a mutable map to count how often each word appears. To read the words, simply use ajava.util.Scanner:
val in = java.util.Scanner(new java.io.File("myfile.txt"))while in.hasNext() doprocessin.next()
Or look at Chapter 9 for a Scalaesque way.
At the end, print out all words and their counts.
Repeat the preceding exercise with an immutable map.
Repeat the preceding exercise with a sorted map, so that the words are printed in sorted order.
Repeat the preceding exercise with ajava.util.TreeMapthat you adapt to the Scala API.
Define a linked hash map that maps"Monday"tojava.util.Calendar.MONDAY, and similarly for the other weekdays. Demonstrate that the elements are visited in insertion order.
Print a table of all Java properties reported by thegetPropertiesmethod of thejava.lang.Systemclass, like this:
java.runtime.name | Java(TM) SE Runtime Environment sun.boot.library.path | /home/apps/jdk1.6.0_21/jre/lib/i386 java.vm.version | 17.0-b16 java.vm.vendor | Sun Microsystems Inc. java.vendor.url | http://java.sun.com/ path.separator | : java.vm.name | Java HotSpot(TM) Server VM
You need to find the length of the longest key before you can print the table.
Write a functionminmax(values: Array[Int])that returns a pair containing the smallest and the largest values in the (nonempty) array.
Reimplement the function from the preceding exercise to return anOptionthat isNoneif the array happens to be empty.
编写一个程序,首先提示用户and last letter, then prints a matching word fromscala.io.Source.fromFile("/usr/share/dict/words").mkString.split("\n"). Usefind. What alternatives do you have for dealing with the returnedOption?
Write a program that demonstrates that the argument of thegetOrElsemethod in theOptionclass is evaluated lazily.
Write a functionlteqgt(values: Array[Int], v: Int)that returns a triple containing the counts of values less thanv, equal tov, and greater thanv.
What happens when you zip together two strings, such as"Hello".zip("World")? Come up with a plausible use case.