Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 103 Maps, Stacks Thomas Kuehne 2016-T2 Lecture 5

Similar presentations


Presentation on theme: "COMP 103 Maps, Stacks Thomas Kuehne 2016-T2 Lecture 5"— Presentation transcript:

1 COMP 103 Maps, Stacks Thomas Kuehne 2016-T2 Lecture 5
Thomas Kuehne, Marcus Frean, Thomas Kuehne School of Engineering and Computer Science, Victoria University of Wellington 2016-T2 Lecture 5

2 RECAP-TODAY RECAP So far we’ve looked at these types of Collection
2 RECAP So far we’ve looked at these types of Collection Bag, List, Set, Queue and Map TODAY More on Map Stack (the last of the Collection types we will look at) Collections of collections of...

3 Maps When declaring and constructing, we must specify two types:
3 When declaring and constructing, we must specify two types: Type of the key, and type of the value private Map<String, PhoneNumber> phoneBook; : phoneBook = new HashMap<String, PhoneNumber> (); 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()

4 Iterating through a Map
4 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 (PhoneNumber num : phonebook.values()) {…. entrySet() → Set of all Map.Entry’s for (Map.Entry<String, Integer> entry : phonebook.entrySet()) { … entry.getKey() … … entry.getValue()… Why Collection of values, not Set of values like the other two? Type for keyvalue pair

5 Example of using Map Find the highest frequency word in a file
5 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) ) );

6 Design the step-by-step solution (algorithm) before you code
Example of using Map 6 // Construct histogram of counts of all words in a file public Map<String, Integer> 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<String, Integer> counts) { // for each word in map // if word has higher count than current maximum count then // record it // return last recorded maximum count word “pseudocode” Design the step-by-step solution (algorithm) before you code

7 Example of using Map 7 // Construct histogram of counts of all words in a file public Map<String, Integer> countWords(Scanner scan){ Map<String, Integer> counts = new HashMap<String, Integer> (); 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;

8 Example of using Map (faster)
8 // Construct histogram of counts of all words in a file public Map<String, Integer> countWords(Scanner scan){ Map<String, Integer> counts = new HashMap<String, Integer> (); while (scan.hasNext()) { String word = scan.next(); Integer frequency = counts.get(word); counts.put(word, frequency == null ? 1 : frequency + 1); } return counts;

9 Iterating through Map: entrySet
9 public String maxCountWord(Map<String, Integer> counts) { String maxWord = null; int maxCount = -1; for (Map.Entry<String, Integer> entry : counts.entrySet() ) { if (entry.getValue() > maxCount) { maxCount = entry.getValue(); maxWord = entry.getKey(); } return maxWord; Map.Entry<K,V> - getKey() - getValue() Map.Entry<K,V> - getKey() - getValue() “public” ⇒ 1 “Alice” ⇒ 1 “eavesdrops” ⇒ 5 “private” ⇒ 1 “Bob” ⇒ 2

10 Stacks Based on the “first in, last out” principle (cf. Queues…)
10 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<Integer> myNums = new Stack<Integer> ();

11 Stacks Stacks have extra operations: push(value), pop(), peek()
11 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!)

12 Stack example Reversing the items from a file:
12 Reversing the items from a file: read and push onto a stack pop them off the stack public void reverseNums(Scanner sc) { Stack<Integer> myNums = new Stack<Integer> (); while (sc.hasNextInt()) myNums.push(sc.nextInt()) while (! myNums.isEmpty()) UI.print(myNums.pop() + “\n”); }

13 Applications of Stacks
13 Programs that deal with programs e.g., program execution, e.g., expression evaluation, (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, or games

14 Stack for evaluating expressions
14 (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”)

15 Summary of these recent collection types
15 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<K,V> Efficiency: you can make queues that are very efficient for the constrained access actions, but would not be efficient for general list operations. Clarity: By declaring it as a queue, you make it clear to other programmers reading/modifying your code what this collection is for and how it should be used. Error prevention: The compiler will stop you from doing illegal operations on a Queue, whereas, if it were a list, you might write them by mistake. Note: if you need to be able to access the middle of the queue, and mess with it, then you will need to use a list. 15

16 Collections of collections?
16 Yes! A collection is an object. Often really useful, for instance, a List of Sets a Map, from Strings into Lists (of...) Examples: A list of sets of ingredients Map of Maps: name -> (workPhone -> #, homePhone -> #)


Download ppt "COMP 103 Maps, Stacks Thomas Kuehne 2016-T2 Lecture 5"

Similar presentations


Ads by Google