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.
1 2
val prices = Map("A" -> 10, "B" -> 20, "C" -> 8) val secondPrices = for((k,v) <- prices) yield (k,0.9*v)
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 = new java.util.Scanner(java.io.File(“myfile.txt”)) while (in.hasNext()) process in.next() Or look at Chapter 9 for a Scalaesque way. At the end, print out all words and their counts.
1 2 3 4 5 6 7 8 9 10 11
// 1. reads words from a File val source = Source.fromFile("../README.md").mkString val words = source.split("\\s+")
// 2. Use a mutable map to count how often each word appears. val wordsCount = new HashMap[String, Int]() for(k <- words) { wordsCount(k) = wordsCount.getOrElse(k,0) + 1 } println(wordsCount.mkString("\n")) //
Repeat the preceding exercise with an immutable map.
1 2 3 4 5 6 7 8
var wordMap2 = Map[String,Int]() val in = new java.util.Scanner(new java.io.File("../README.MD"))
Repeat the preceding exercise with a java.util.TreeMap that you adapt to the Scala API.
1 2 3 4 5 6 7 8
val wordMap4:scala.collection.mutable.Map[String,Int] = new java.util.TreeMap[String,Int] val in = new java.util.Scanner(new java.io.File("../README.MD"))
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.