Unformatted text preview:

CompSci 635.1Mapsÿ Maps are another way of organizing dataÿ Keys and Values Each key maps to a value Some keys can map to the same value Can change the value a key maps toCompSci 635.2Exampleÿ Each student could be mapped to their favorite ice cream flavorCompSci 635.3Implementing a Mapÿ We will use TreeMap in Javaÿ Example:Map<String, String> fav= new TreeMap<String, String>();ÿ Keys map to valuesCompSci 635.4To use a Mapÿ Put in a key and its valuefav.put(”Forbes”, ”Strawberry”);ÿ Get a value for a keyval = fav.get(”Forbes”);ÿ Change value for keyfav.put(”Astrachan”, ”Coffee Mocha”);CompSci 635.5Change Astrachan’s valueCompSci 635.6Value could be a setCompSci 635.7Classwork todayÿ File of words Determine number times each words appears For each word, determine all line numbers it appears on For each alphabetical letter, determine all the words that start with that letter.CompSci 635.8First look at methods givenÿ mainÿ getWordcounts Given a Scanner bound to a file Return a Map of words to countsÿ printResults Given a map print key followed by valueCompSci 635.9Wordlines: getWordCountspublic Map<String, Integer> getWordCounts (Scanner input) {Map<String,Integer> results = new TreeMap<String,Integer>();while (input.hasNext()) {String word = input.next();Integer count = results.get(word);if (count == null){results.put(word, 1);}else {results.put(word, count + 1);}}return results;}CompSci 635.10Wordlines: printResultspublic void printResults(Map<String, ?> results) {for (String key : results.keySet()) {System.out.println(key + "\t" +results.get(key).toString());}// OR:for (Map.Entry<String, ?> current : results.entrySet()) {System.out.println(current.getKey() + "\t"+ current.getValue());}}CompSci 635.11OutputCompSci 635.12Todo: getLineNumbersÿ Map each word to a set of line numbers it occurs onCompSci 635.13Todo: getFrequenciesÿ Map each letter of alphabet to


View Full Document

Duke CPS 006 - Maps

Download Maps
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Maps and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Maps 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?