Presentation is loading. Please wait.

Presentation is loading. Please wait.

CompSci 6 35.1 Maps  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.

Similar presentations


Presentation on theme: "CompSci 6 35.1 Maps  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."— Presentation transcript:

1 CompSci 6 35.1 Maps  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 to

2 CompSci 6 35.2 Example  Each student could be mapped to their favorite ice cream flavor

3 CompSci 6 35.3 Implementing a Map  We will use TreeMap in Java  Example: Map fav = new TreeMap ();  Keys map to values

4 CompSci 6 35.4 To use a Map  Put in a key and its value fav.put(”Forbes”, ”Strawberry”);  Get a value for a key val = fav.get(”Forbes”);  Change value for key fav.put(”Astrachan”, ”Coffee Mocha”);

5 CompSci 6 35.5 Change Astrachan’s value

6 CompSci 6 35.6 Value could be a set

7 CompSci 6 35.7 Classwork 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.

8 CompSci 6 35.8 First 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 value

9 CompSci 6 35.9 Wordlines: getWordCounts public Map getWordCounts (Scanner input) { Map results = new TreeMap (); 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; }

10 CompSci 6 35.10 Wordlines: printResults public void printResults(Map results) { for (String key : results.keySet()) { System.out.println(key + "\t" + results.get(key).toString()); } // OR: for (Map.Entry current : results.entrySet()) { System.out.println(current.getKey() + "\t" + current.getValue()); }

11 CompSci 6 35.11 Output

12 CompSci 6 35.12 Todo: getLineNumbers  Map each word to a set of line numbers it occurs on

13 CompSci 6 35.13 Todo: getFrequencies  Map each letter of alphabet to words


Download ppt "CompSci 6 35.1 Maps  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."

Similar presentations


Ads by Google