COMP T2 Lecture 5 School of Engineering and Computer Science, Victoria University of Wellington Thomas Kuehne Maps, Stacks Thomas Kuehne, Marcus Frean,
RECAP So far we’ve looked at these types of Collection Bag, List, Set, Queue and Map TODAY Stack (the last of the Collection types we will look at) Collections of collections of... RECAP-TODAY 2
Maps When declaring and constructing, we must specify two types: Type of the key, and type of the value private Map phoneBook; : phoneBook = new HashMap (); Operations: get(key) → returns value associated with key (or null) put(key, value) → sets the value associated with key (and returns the old value, if any) remove(key) → removes the key and associated value (and returns the old value, if any) containsKey(key) → boolean size() 3
Iterating through a Map How do you iterate through a Map ? (e.g,. to print it out) A Map isn’t just a collection of single items! ⇒ could iterate through the collection of keys ⇒ could iterate through the collection of values ⇒ could iterate through the collection of key-value pairs Java Collection library’s Map allows all of the above! keySet()→ Set of all keys for (String name : phonebook.keySet()) {…. values()→ Collection of all values for (Integer num : phonebook.values()) {…. entrySet()→ Set of all Map.Entry’s for (Map.Entry entry : phonebook.entrySet()) { … entry.getKey() … … entry.getValue()… 4 Why Collection of values, not Set of values like the other two ? Type for key value pair
Example of using Map Find the highest frequency word in a file ⇒ must count frequency of every word i.e., need to associate a count (int) with each word (String) ⇒ use a Map of “word count” pairs Two Steps: construct the counts of each word:countWords(file) → map find the highest count:maxCountWord(map) → word UI.println( maxCountWord( countWords(file) ) ); 5
Example of using Map (similar to Assign#2) // Construct histogram of counts of all words in a file public Map countWords(Scanner sc) { // construct new map // for each word in file // if word is in the map, increment its count // else, put it in map with a count of 1 // return map } // Find word in histogram with highest count public String maxCountWord(Map counts) { // for each word in map // if word has higher count than current maximum count, record it // return last recorded maximum count word } 6 “pseudocode” Design the step- by-step solution (algorithm) before you code “pseudocode” Design the step- by-step solution (algorithm) before you code
Example of using Map // Construct histogram of counts of all words in a file public Map countWords(Scanner scan){ Map counts = new HashMap (); while (scan.hasNext()) { String word = scan.next(); if ( counts.containsKey(word) ) counts.put(word, counts.get(word)+1); else counts.put(word, 1); } return counts; } 7
Example of using Map (faster) // Construct histogram of counts of all words in a file public Map countWords(Scanner scan){ Map counts = new HashMap (); while (scan.hasNext()) { String word = scan.next(); Integer frequency = counts.get(word); counts.put(word, frequency == null ? 1 : frequency + 1); } return counts; } 8
Iterating through Map: entrySet public String maxCountWord(Map counts) { String maxWord = null; int maxCount = -1; for (Map.Entry entry : counts.entrySet() ) { if (entry.getValue() > maxCount) { maxCount = entry.getValue(); maxWord = entry.getKey(); } } return maxWord; } “public” ⇒ 1 “Bob” ⇒ 2 “Alice” ⇒ 1 “eavesdrops” ⇒ 5 “private” ⇒ 1 Map.Entry - getKey() - getValue() 9 Map.Entry - getKey() - getValue()
Stacks Based on the “first in, last out” principle (cf. Queues…) A special kind of List: Constrained access: add, get, and remove only from one end We should have a Stack interface, and different implementations of it (ArrayStack, LinkedStack, etc.), but... In Java’s Collections library, it is a class that implements List (actually, it extends Vector) So you make one like this: Stack myNums = new Stack (); 10
Stacks Stacks have extra operations: push(value), pop(), peek() push(value): Put value on top of stack pop():Removes and returns top of stack peek():Returns top of stack, without removing plus the other List operations… ( oops! ) 11
Stacks example Reversing the items from a file: read and push onto a stack pop them off the stack public void reverseNums(Scanner sc){ Stack myNums = new Stack (); while (sc.hasNextInt()) myNums.push(sc.nextInt()) while (! myNums.isEmpty()) UI.print(myNums.pop() + “\n”); } 12
Applications of Stacks Programs that deal with programs e.g., program execution, e.g., expression execution, (6 + 4) * ((10 * √ 64) – ( √ 81/ 3)) working on subtasks, returning to previous task. Processing files of structured (nested) data. e.g., reading files of with structured markup (HTML, XML,…) Undo in editors 13
Stack for evaluating expressions (6 + 4) * ((10 * √ 64) – ( √ 81/ 3)) ⇒ ( (6, 4)+, ((10, (64) √ ) *, ((81) √, 3)/ )- )* ⇒ √ * 81 √ 3 / - * Algorithm: if operand:push on stack if operator:pop arguments from stack compute value push on stack if done:pop answer from stack Postfix order (also known as “Reverse Polish notation”) 14
Summary of these recent collection types Queue First in, first out (FIFO) Always remove from one end Ordinary queue: add at the opposed end Priority queue: add anywhere, according to priority Stack First in, last out (FILO) [Java: No Stack interface, just a class, named “Stack”, with lax control] Map Key Value pairs Three ways to iterate:over set of Keys, over collection of Values, over set of Key Value pairs Key Value pairs represented using Map.Entry 15
Collections of collections? Yes! A collection is an object. Often really useful, for instance, a List of Sets a Map, from Strings into Lists (of...) 16