Top Banner
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others. CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2
49

CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

Aug 08, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

2

Learning Goals• KnowhowtostoredatainandretrievedatafromaHashMap.

Page 3: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

3

Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap

Page 4: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

4

Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap

Page 5: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

8

ArrayLists + Primitives = 💔

Primitive “Wrapper”Classint Integerdouble Doubleboolean Booleanchar Character

Page 9: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

10

Example: Opening Crawl

Page 11: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

11

Example: Planner• Let’swriteaprogramthatemulatestheStarWars“openingcrawl”

– Theprogramfirstreadsinatextfile– Itthenanimatesthistextflowingupwards

Page 12: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

12

Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap

Page 13: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

14

How Is Webpage Lookup So Fast?

Page 15: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

15

Introducing… HashMaps!•Avariabletypethatrepresentsacollectionofkey-valuepairs

•Youaccessvaluesbykey•Keysandvaluescanbeanytypeofobject•Resizable– canaddandremovepairs•Hashelpfulmethodsforsearchingforkeys

Page 16: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

17

Our First HashMap

HashMap<String, String> myHashMap = new HashMap<>();

import java.util.*;

Page 18: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

18

Our First HashMap

HashMap<String, String> myHashMap = new HashMap<>();

Page 19: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

21

Our First HashMap

HashMap<String, String> myHashMap = new HashMap<>();

Page 22: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

22

Our First HashMap

HashMap<String, String> myHashMap = new HashMap<>();

Page 23: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

23

Our First HashMap

HashMap<String, String> myHashMap = new HashMap<>();

Page 24: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

36

Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap

Page 37: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

37

Exercise: Dictionary• Writeaprogramtoreadadictionaryofwordsanddefinitionsfromafile,thenprompttheuserforwordstolookup.

– Exampledatafromthedictionaryinputfile:

abateto lessen; to subsideperniciousharmful, injurious

• HowcanaHashMap helpussolvethisproblem?

Page 38: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

38

Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap

Page 39: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

42

Plan for today•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending•Recap

Page 43: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

44

Recap•Recap:ArrayLists•HashMaps•Practice:Dictionary•HashMaps asCounters•Practice:What’sTrending

Nexttime:definingourownvariabletypes

Page 45: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

Overflow(extra)slides

Page 46: CS 106A, Lecture 20 HashMaps - Stanford University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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 University€¦ · CS 106A, Lecture 20 HashMaps suggested reading: Java Ch. 13.2. 2 Learning Goals •Know how to store data in and retrieve

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]: ");

}