CS 106A, Lecture 20 HashMaps - Stanford...
Transcript of CS 106A, Lecture 20 HashMaps - Stanford...
![Page 1: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/1.jpg)
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
CS106A,Lecture20HashMaps
suggestedreading:JavaCh.13.2
![Page 2: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/2.jpg)
2
Learning Goals• KnowhowtostoredatainandretrievedatafromaHashMap.
![Page 3: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/3.jpg)
3
Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap
![Page 4: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/4.jpg)
4
Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap
![Page 5: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/5.jpg)
5
Our First ArrayList// Create an (initially empty) listArrayList<String> list = new ArrayList<>();
// Add an element to the backlist.add("Hello"); // now size 1
list.add("there!"); // now size 2
“Hello”
“Hello” “there!”
![Page 6: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/6.jpg)
6
ArrayList Methodslist.add(value); appendsvalueatendoflistlist.add(index, value); insertsgivenvaluejustbeforethegivenindex,
shiftingsubsequentvaluestotherightlist.clear(); removesallelementsofthelistlist.get(index) returnsthevalueatgivenindexlist.indexOf(value) returnsfirstindexwheregivenvalueisfoundinlist
(-1ifnotfound)list.isEmpty() returnstrue ifthelistcontainsnoelementslist.remove(index); removes/returnsvalueatgivenindex,shifting
subsequentvaluestotheleftlist.remove(value); removesthefirstoccurrenceofthevalue,ifanylist.set(index, value); replacesvalueatgivenindexwithgivenvaluelist.size() returnsthenumberofelementsinthelistlist.toString() returnsastringrepresentationofthelist
suchas"[3, 42, -7, 15]"
![Page 7: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/7.jpg)
7
Insert/remove• Ifyouinsert/removeinthefrontormiddleofalist,elementsshift tofit.
list.add(2, 42);• shiftelementsrighttomakeroomforthenewelement
list.remove(1);• shiftelementslefttocoverthespaceleftbytheremovedelement
index 0 1 2 3 4value 3 8 9 7 5
index 0 1 2 3 4 5value 3 8 42 9 7 5
index 0 1 2 3 4 5value 3 8 42 9 7 5
index 0 1 2 3 4value 3 42 9 7 5
![Page 8: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/8.jpg)
8
ArrayLists + Primitives = 💔
Primitive “Wrapper”Classint Integerdouble Doubleboolean Booleanchar Character
![Page 9: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/9.jpg)
9
ArrayLists + Wrappers = ❤// Use wrapper classes when making an ArrayListArrayList<Integer> list = new ArrayList<>();
// Java converts Integer <-> int automatically!int num = 123;list.add(num);
int first = list.get(0); // 123
Conversion happens automatically!
![Page 10: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/10.jpg)
10
Example: Opening Crawl
![Page 11: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/11.jpg)
11
Example: Planner• Let’swriteaprogramthatemulatestheStarWars“openingcrawl”
– Theprogramfirstreadsinatextfile– Itthenanimatesthistextflowingupwards
![Page 12: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/12.jpg)
12
Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap
![Page 13: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/13.jpg)
13
Limitations of Lists• Canonlylookupbyindex (int),notbyString,etc.• Cumbersomeforpreventingduplicateinformation• Slowforlookup
index 0 1 2 3 4 5 6 7 8 9
value 12 49 -2 26 5 17 -6 84 72 3
![Page 14: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/14.jpg)
14
How Is Webpage Lookup So Fast?
![Page 15: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/15.jpg)
15
Introducing… HashMaps!•Avariabletypethatrepresentsacollectionofkey-valuepairs
•Youaccessvaluesbykey•Keysandvaluescanbeanytypeofobject•Resizable– canaddandremovepairs•Hashelpfulmethodsforsearchingforkeys
![Page 16: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/16.jpg)
16
HashMap Examples•Phonebook:name->phonenumber•Searchengine: URL->webpage•Dictionary:word->definition•Bank:account#->balance•SocialNetwork:name->profile•Counter:text->#occurrences•Andmanymore…
![Page 17: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/17.jpg)
17
Our First HashMap
HashMap<String, String> myHashMap = new HashMap<>();
import java.util.*;
![Page 18: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/18.jpg)
18
Our First HashMap
HashMap<String, String> myHashMap = new HashMap<>();
![Page 19: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/19.jpg)
19
Our First HashMap
HashMap<String, String> myHashMap = new HashMap<>();
Type of keys your HashMap will store.
![Page 20: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/20.jpg)
20
Our First HashMap
HashMap<String, String> myHashMap = new HashMap<>();
Type of values your HashMap will store.
![Page 21: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/21.jpg)
21
Our First HashMap
HashMap<String, String> myHashMap = new HashMap<>();
![Page 22: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/22.jpg)
22
Our First HashMap
HashMap<String, String> myHashMap = new HashMap<>();
![Page 23: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/23.jpg)
23
Our First HashMap
HashMap<String, String> myHashMap = new HashMap<>();
![Page 24: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/24.jpg)
24
Our First HashMap - Put// Create an (initially empty) HashMapHashMap<String, String> map = new HashMap<>();map.put("dog", "bark"); // Add a key-value pairmap.put("cat", "meow"); // Add another pairmap.put("seal", "ow ow"); // Add another pairmap.put("seal", "ow ow ow"); // Overwrites!
Keys:
Values:
“dog” “cat”“seal”
“owow”
“owowow”
![Page 25: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/25.jpg)
25
Our First HashMap - Get...String s = map.get("dog"); // Get a value for a keyString s = map.get("cat"); // Get a value for a keyString s = map.get("fox"); // null
Keys:
Values:
“dog” “cat”“seal”
“owowow”
![Page 26: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/26.jpg)
26
Our First HashMap - Remove...map.remove("dog"); // Remove pair from mapmap.remove("seal"); // Remove pair from mapmap.remove("fox"); // Does nothing if not in map
Keys:
Values:
“dog” “cat”“seal”
“owow”
“owowow”
![Page 27: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/27.jpg)
27
Review: HashMap Operations• m.put(key, value); Addsakey/valuepairtothemap.
m.put("Eric", "650-123-4567"); • Replacesanypreviousvalueforthatkey.
• m.get(key) Returnsthevaluepairedwiththegivenkey.String phoneNum = m.get("Jenny"); // "867-5309"• Returnsnullifthekeyisnotfound.
• m.remove(key); Removesthegivenkeyanditspairedvalue.
m.remove("Rishi");• Hasnoeffectifthekeyisnotinthemap.
key value"Jenny”→"867-5309""Mehran"→"123-4567""Marty"→"685-2181""Chris”→"947-2176"
![Page 28: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/28.jpg)
28
Using HashMaps• AHashMap allowsyoutogetfromonehalfofapairtotheother.
– Remembersonepieceofinformationabouteverykey.
– Later,wecansupplyonlythekeyandgetbacktherelatedvalue:Allowsustoask:WhatisJenny’sphonenumber?
HashMap
m.get("Jenny")
"867-5309"
HashMap
// key valuem.put("Jenny", "867-5309");
![Page 29: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/29.jpg)
29
Practice: Map MysteryQ: Whatarethecorrectmapcontentsafterthefollowingcode?
HashMap<String, String> map = new HashMap<>();map.put("K", "Schwarz");map.put("C", "Lee");map.put("M", "Sahami");map.put("M", "Stepp");map.remove("Stepp");map.remove("K");map.put("J", "Cain");map.remove("C, Lee");
A. {C=Lee, J=Cain, M=Stepp, M=Sahami}B. {C=Lee, J=Cain, M=Stepp}C. {J=Cain M=Sahami, M=Stepp}D. {J=Cain, K=Schwarz, M=Sahami}E. other
![Page 30: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/30.jpg)
30
Practice: Map MysteryQ: Whatarethecorrectmapcontentsafterthefollowingcode?
HashMap<String, String> map = new HashMap<>();map.put("K", "Schwarz");map.put("C", "Lee");map.put("M", "Sahami");map.put("M", "Stepp");map.remove("Stepp");map.remove("K");map.put("J", "Cain");map.remove("C, Lee");
Keys:
Values:
“K” “C”“M”
“Sahami”
![Page 31: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/31.jpg)
31
Practice: Map MysteryQ:Whatarethecorrectmapcontentsafterthefollowingcode?
HashMap<String, String> map = new HashMap<>();map.put("K", "Schwarz");map.put("C", "Lee");map.put("M", "Sahami");map.put("M", "Stepp");map.remove("Stepp");map.remove("K");map.put("J", "Cain");map.remove("C, Lee");
Keys:
Values:
“K” “C”“M”
“Stepp”
![Page 32: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/32.jpg)
32
Practice: Map MysteryQ:Whatarethecorrectmapcontentsafterthefollowingcode?
HashMap<String, String> map = new HashMap<>();map.put("K", "Schwarz");map.put("C", "Lee");map.put("M", "Sahami");map.put("M", "Stepp");map.remove("Stepp");map.remove("K");map.put("J", "Cain");map.remove("C, Lee");
Keys:
Values:
“K” “C”“M”
“Stepp”
![Page 33: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/33.jpg)
33
Practice: Map MysteryQ:Whatarethecorrectmapcontentsafterthefollowingcode?
HashMap<String, String> map = new HashMap<>();map.put("K", "Schwarz");map.put("C", "Lee");map.put("M", "Sahami");map.put("M", "Stepp");map.remove("Stepp");map.remove("K");map.put("J", "Cain");map.remove("C, Lee");
Keys:
Values:
“C”“M”
“Stepp”
![Page 34: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/34.jpg)
34
Practice: Map MysteryQ:Whatarethecorrectmapcontentsafterthefollowingcode?
HashMap<String, String> map = new HashMap<>();map.put("K", "Schwarz");map.put("C", "Lee");map.put("M", "Sahami");map.put("M", "Stepp");map.remove("Stepp");map.remove("K");map.put("J", "Cain");map.remove("C, Lee");
Keys:
Values:
“C”“M”
“Stepp”
“J”
![Page 35: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/35.jpg)
35
Practice: Map MysteryQ:Whatarethecorrectmapcontentsafterthefollowingcode?
HashMap<String, String> map = new HashMap<>();map.put("K", "Schwarz");map.put("C", "Lee");map.put("M", "Sahami");map.put("M", "Stepp");map.remove("Stepp");map.remove("K");map.put("J", "Cain");map.remove("C, Lee");
Keys:
Values:
“C”“M”
“Stepp”
“J”
![Page 36: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/36.jpg)
36
Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap
![Page 37: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/37.jpg)
37
Exercise: Dictionary• Writeaprogramtoreadadictionaryofwordsanddefinitionsfromafile,thenprompttheuserforwordstolookup.
– Exampledatafromthedictionaryinputfile:
abateto lessen; to subsideperniciousharmful, injurious
• HowcanaHashMap helpussolvethisproblem?
![Page 38: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/38.jpg)
38
Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap
![Page 39: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/39.jpg)
39
Iterating Over HashMaps...for (String key : map.keySet()) {String value = map.get(key);// do something with key/value pair...
}// Keys occur in an unpredictable order!
Keys:
Values:
“dog” “cat”“seal”
“owowow”
![Page 40: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/40.jpg)
40
Counting Exercise• Writeaprogramtocountthenumberofoccurrencesofeachuniquewordinalargetextfile(e.g.MobyDick ).
– Allowtheusertotypeawordandreporthowmanytimesthatwordappearedinthebook.
– Reportallwordsthatappearedinthebookatleast500times.
• Howcanamap helpussolvethisproblem?– Thinkaboutscanningoverafilecontainingthisinputdata:
To be or not to be or to be a bee not two bees ...^
![Page 41: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/41.jpg)
41
Maps and Tallying• amapcanbethoughtofasgeneralizationofatallyingarray
– the"index"(key)doesn'thavetobeanint
– countdigits:22092310907
// (R)epublican, (D)emocrat, (I)ndependent– countvotes: "RDDDDDDRRRRRDDDDDDRDRRIRDRRIRDRRID"
index 0 1 2 3 4 5 6 7 8 9value 3 1 3 0 0 0 0 1 0 2
key "R" "D" "I"value 16 14 3
key value"R" →16"D" →14"I" →3
![Page 42: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/42.jpg)
42
Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap
![Page 43: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/43.jpg)
43
Practice: What's Trending?• Socialmediacanbeusedtomonitorpopularconversationtopics.• Writeaprogramtocountthefrequencyof#hashtags intweets:
– Readsavedtweetsfromalargetextfile.– Reporthashtagsthatoccuratleast15times.
• Howcanamap helpussolvethisproblem?Giventhesehashtags… Wewanttostore...
#stanford#summer#california#stanford
"#stanford" → 2"#summer" → 1"#california" → 1
![Page 44: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/44.jpg)
44
Recap•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending
Nexttime:definingourownvariabletypes
![Page 45: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/45.jpg)
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
Overflow(extra)slides
![Page 46: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/46.jpg)
46
Anagram exercise• Writeaprogramtofindallanagrams ofawordtheusertypes.
Type a word [Enter to quit]: scaredAnagrams of scared:cadres cedars sacred scared
• Howcanamap helpussolvethisproblem?
![Page 47: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/47.jpg)
47
Anagram observation• Everywordhasasortedform whereitslettersarearrangedintoalphabeticalorder.
"fare" ® "aefr""fear" ® "aefr""swell" ® "ellsw""wells" ® "ellsw"
• Noticethatanagramshavethesamesortedformaseachother.– Howisthishelpfulforsolvingtheproblem?– SupposeweweregivenasortLettersmethod.Howtouseit?
![Page 48: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/48.jpg)
48
Anagram solutionpublic String sortLetters(String s) { ... } // assume this exists...
// build map of {sorted form => all words with that sorted form}HashMap<String, String> anagrams = new
HashMap<String, String>();try {
Scanner input = new Scanner(new File("dictionary.txt"));while (true) {
String word = input.next();String sorted = sortLetters(word); // "acders"if (anagrams.containsKey(sorted)) {
String rest = anagrams.get(sorted);anagrams.put(sorted, rest + " " + word); // append
} else {anagrams.put(sorted, word); // new k/v pair
}// {"acders" => "cadres caders sacred scared", ...}
}} catch (FileNotFoundException fnfe) {
println("Error reading file: " + fnfe);}
![Page 49: CS 106A, Lecture 20 HashMaps - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/... · 2017-08-01 · •A HashMapallows you to get from one half of a pair](https://reader035.fdocuments.us/reader035/viewer/2022070920/5fb93c0a7b2eef408762ab06/html5/thumbnails/49.jpg)
49
Anagram solution cont'd.// prompt user for words and look up anagrams in mapString word = readLine("Type a word [Enter to quit]: ");while (word.length() > 0) {
String sorted = sortLetters(word.toLowerCase());if (anagrams.containsKey(sorted)) {
println("Anagrams of " + word + ":");println(anagrams.get(sorted));
} else {println("No anagrams for " + word + ".");
}word = readLine("Type a word [Enter to quit]: ");
}