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 a java.util.Scanner:
val in = java.util.Scanner(new java.io.File("myfile.txt")) while in.hasNext() do process in.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 a java.util.TreeMap that you adapt to the Scala API.
Define a linked hash map that maps "Monday" to java.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 the getProperties method of the java.lang.System class, 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 function minmax(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 an Option that is None if the array happens to be empty.
Write a program that prompts the user for a first and last letter, then prints a matching word from scala.io.Source.fromFile("/usr/share/dict/words").mkString.split("\n"). Use find. What alternatives do you have for dealing with the returned Option?
Write a program that demonstrates that the argument of the getOrElse method in the Option class is evaluated lazily.
Write a function lteqgt(values: Array[Int], v: Int) that returns a triple containing the counts of values less than v, equal to v, and greater than v.
What happens when you zip together two strings, such as "Hello".zip("World")? Come up with a plausible use case.