CSE 373 Java Collection Framework, Part 2: Priority Queue, Map

Slides:



Advertisements
Similar presentations
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Advertisements

CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
CSE 143 Lecture 15 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Java Collections. Collections, Iterators, Algorithms CollectionsIteratorsAlgorithms.
CSE 143 Lecture 15 Sets and Maps; Iterators reading: ; 13.2; 15.3; 16.5 slides adapted from Marty Stepp
CS Collection and Input/Output Classes CS 3331 Fall 2009.
Building Java Programs Chapter 11 Java Collections Framework.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
(c) University of Washington14-1 CSC 143 Java Collections.
111 © 2002, Cisco Systems, Inc. All rights reserved.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Building Java Programs Chapter 11 Lecture 11-1: Sets and Maps reading:
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
CSE 143 Lecture 14 (B) Maps and Grammars reading: 11.3 slides created by Marty Stepp
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Building Java Programs Chapter 11 Java Collections Framework Copyright (c) Pearson All rights reserved.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
CSE 143 Lecture 14 Maps/Sets; Grammars reading: slides adapted from Marty Stepp and Hélène Martin
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
CSE 143 Lecture 12: Sets and Maps reading:
CSE 373: Data Structures and Algorithms Lecture 16: Hashing III 1.
CSE 143 Lecture 11: Sets and Maps reading:
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
CSE 143 Lecture 16 Iterators; Grammars reading: 11.1, 15.3, 16.5 slides created by Marty Stepp
Building Java Programs Chapter 11 Java Collections Framework Copyright (c) Pearson All rights reserved.
Slides by Donald W. Smith
Using the Java Collection Libraries COMP 103 # T2
CSc 110, Autumn 2016 Lecture 26: Sets and Dictionaries
Building Java Programs
CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs)
CSE 373 Implementing a Stack/Queue as a Linked List
Chapter 19 Java Data Structures
Wednesday Notecards. Wednesday Notecards Wednesday Notecards.
slides created by Marty Stepp and Hélène Martin
CSc 110, Autumn 2016 Lecture 27: Sets and Dictionaries
CSc 110, Spring 2018 Lecture 32: Sets and Dictionaries
Week 2: 10/1-10/5 Monday Tuesday Wednesday Thursday Friday
Road Map CS Concepts Data Structures Java Language Java Collections
Back to Collections Lists: Sets Maps ArrayList LinkedList
Sets (11.2) set: A collection of unique values (no duplicates allowed) that can perform the following operations efficiently: add, remove, search (contains)
CSE 373: Data Structures and Algorithms
Part of the Collections Framework
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
slides adapted from Marty Stepp
slides created by Marty Stepp and Hélène Martin
Iteration Abstraction
Welcome to CSE 143! Go to pollev.com/cse143.
Exercise Write a program that counts the number of unique words in a large text file (say, Moby Dick or the King James Bible). Store the words in a collection.
CS2110: Software Development Methods
slides created by Marty Stepp
CSE 143 Lecture 25 Set ADT implementation; hashing read 11.2
Sets (11.2) set: A collection of unique values (no duplicates allowed) that can perform the following operations efficiently: add, remove, search (contains)
CSE 143 Lecture 25 Advanced collection classes
Lecture 3: Maps and Iterators
slides created by Marty Stepp
Building Java Programs
CSE 143 Lecture 15 Sets and Maps; Iterators reading: ; 13.2
CSE 143 Lecture 8 Iterators; Comparable reading: 11.2; 10.2
slides adapted from Marty Stepp and Hélène Martin
Lecture 3: Maps and Iterators
CSE 373 Java Collection Framework reading: Weiss Ch. 3, 4.8
Iterators Dan Fleck.
CSE 143 Lecture 21 Advanced List Implementation
CS 240 – Advanced Programming Concepts
CSE 373 Set implementation; intro to hashing
Presentation transcript:

CSE 373 Java Collection Framework, Part 2: Priority Queue, Map slides created by Marty Stepp http://www.cs.washington.edu/373/ © University of Washington, all rights reserved.

Priority queue ADT priority queue: a collection of ordered elements that provides fast access to the minimum (or maximum) element usually implemented using a tree structure called a heap priority queue operations: add adds in order; O(log N) worst peek returns minimum value; O(1) always remove removes/returns minimum value; O(log N) worst isEmpty, clear, size, iterator O(1) always

Java's PriorityQueue class public class PriorityQueue<E> implements Queue<E> Queue<String> pq = new PriorityQueue<String>(); pq.add("Stuart"); pq.add("Marty"); ... Method/Constructor Description Runtime PriorityQueue<E>() constructs new empty queue O(1) add(E value) adds value in sorted order O(log N ) clear() removes all elements iterator() returns iterator over elements peek() returns minimum element remove() removes/returns min element

Priority queue ordering For a priority queue to work, elements must have an ordering in Java, this means implementing the Comparable interface many existing types (Integer, String, etc.) already implement this if you store objects of your own types in a PQ, you must implement it TreeSet and TreeMap also require Comparable types public class Foo implements Comparable<Foo> { … public int compareTo(Foo other) { // Return > 0 if this object is > other // Return < 0 if this object is < other // Return 0 if this object == other }

The Map ADT map: Holds a set of unique keys and a collection of values, where each key is associated with one value. a.k.a. "dictionary", "associative array", "hash" basic map operations: put(key, value): Adds a mapping from a key to a value. get(key): Retrieves the value mapped to the key. remove(key): Removes the given key and its mapped value. myMap.get("Juliet") returns "Capulet"

Map concepts a map can be thought of as generalization of a tallying array the "index" (key) doesn't have to be an int count digits: 22092310907 // (R)epublican, (D)emocrat, (I)ndependent count votes: "RDDDDRRRRRDDDDDDRDRRIRDRRIRDRRID" index 1 2 3 4 5 6 7 8 9 value "R" "D" "I" 15 3 14 keys values key "R" "D" "I" value 15 14 3

Map implementation in Java, maps are represented by Map interface in java.util Map is implemented by the HashMap and TreeMap classes HashMap: implemented using an array called a "hash table"; extremely fast: O(1) ; keys are stored in unpredictable order TreeMap: implemented as a linked "binary tree" structure; very fast: O(log N) ; keys are stored in sorted order A map requires 2 type parameters: one for keys, one for values. // maps from String keys to Integer values Map<String, Integer> votes = new HashMap<String, Integer>();

Map methods put(key, value) adds a mapping from the given key to the given value; if the key already exists, replaces its value with the given one get(key) returns the value mapped to the given key (null if not found) containsKey(key) returns true if the map contains a mapping for the given key remove(key) removes any existing mapping for the given key clear() removes all key/value pairs from the map size() returns the number of key/value pairs in the map isEmpty() returns true if the map's size is 0 toString() returns a string such as "{a=90, d=60, c=70}" keySet() returns a set of all keys in the map values() returns a collection of all values in the map putAll(map) adds all key/value pairs from the given map to this map equals(map) returns true if given map has the same mappings as this one

Using maps A map allows you to get from one half of a pair to the other. Remembers one piece of information about every index (key). Later, we can supply only the key and get back the related value: Allows us to ask: What is Joe's phone number? // key value put("Joe", "206-685-2181") Map get("Joe") Map "206-685-2181"

Maps vs. sets A set is like a map from elements to boolean values. Set: Is Joe found in the set? (true/false) Map: What is Joe's phone number? "Joe" Set true false "Joe" Map "206-685-2181"

keySet and values keySet method returns Set of all keys in map can loop over the keys in a foreach loop can get each key's associated value by calling get on the map Map<String, Integer> ages = new TreeMap<String, Integer>(); ages.put("Joe", 57); ages.put("Geneva", 2); // ages.keySet() returns Set<String> ages.put("Vicki", 19); for (String name : ages.keySet()) { // Geneva -> 2 int age = ages.get(name); // Joe -> 57 System.out.println(name + " -> " + age); // Vicki -> 19 } values method returns Collection of all values in map ages.values() above returns [2, 57, 19] can loop over the values with a for-each loop no easy way to get from a value back to its associated key(s)

Collections summary It is important to be able to choose a collection properly based on the capabilities needed and constraints of the problem to solve. collection ordering benefits weaknesses array by index fast; simple little functionality; cannot resize ArrayList by insertion, by index random access; fast to modify at end slow to modify in middle/front LinkedList fast to modify at both ends poor random access TreeSet sorted order sorted; O(log N) must be comparable HashSet unpredictable very fast; O(1) unordered LinkedHashSet order of insertion uses extra memory TreeMap HashMap LinkedHashMap PriorityQueue natural/comparable fast ordered access

Choosing a collection see also: http://initbinder.com/bunker/wp-content/uploads/2011/03/collections.png

Compound collections You will often find that you want a collection of collections: a list of lists; a map of strings to lists; a queue of sets; ... Example: how would you store people's friends? i.e., I need to quickly look up the names of all of Jimmy's buddies, or test whether a given person is a friend of Jimmy's or not. // don't forget to initialize each Set of friends Map<String, Set<String>> pals = new HashMap<String, Set<String>>(); pals.put("Jimmy", new HashSet<String>()); pals.get("Jimmy").add("Bill"); pals.get("Jimmy").add("Katherine"); pals.get("Jimmy").add("Stuart");

Iterators (11.1) iterator: An object that allows a client to traverse the elements of any collection. Remembers a position, and lets you: get the element at that position advance to the next position remove the element at that position "the" "to" "from" "we" index 1 2 3 4 5 6 7 8 9 value 12 size set list current element: 9 current index: 2 iterator current element: "from" next element: "the" iterator

Iterator methods Iterator interface in java.util every collection has an iterator() method that returns an iterator over its elements Set<String> set = new HashSet<String>(); ... Iterator<String> itr = set.iterator(); hasNext() returns true if there are more elements to examine next() returns the next element from the collection (throws a NoSuchElementException if there are none left to examine) remove() removes the last value returned by next() (throws an IllegalStateException if you haven't called next() yet)

Iterator example Set<Integer> scores = new TreeSet<Integer>(); scores.add(94); scores.add(38); // Jenny scores.add(87); scores.add(43); // Marty scores.add(72); ... Iterator<Integer> itr = scores.iterator(); while (itr.hasNext()) { int score = itr.next(); System.out.println("The score is " + score); // eliminate any failing grades if (score < 60) { itr.remove(); } System.out.println(scores); // [72, 87, 94]

A surprising example What's bad about this code? List<Integer> list = new LinkedList<Integer>(); ... (add lots of elements) ... for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } data next 42 data next -3 front = data next 17 element 0 element 1 element 2

Iterators and linked lists Iterators are particularly useful with linked lists. The previous code is O(N2) because each call on get must start from the beginning of the list and walk to index i. Using an iterator, the same code is O(N). The iterator remembers its position and doesn't start over each time. data next 42 data next -3 front = data next 17 element 0 element 1 element 2 current element: -3 current index: 1 iterator

ListIterator lists have a more powerful ListIterator with more methods ListIterator<String> li = myList.listIterator(); lists have a more powerful ListIterator with more methods can iterate forwards or backwards can add/set element values (efficient for linked lists) add(value) inserts an element just after the iterator's position hasPrevious() true if there are more elements before the iterator nextIndex() the index of the element that would be returned the next time next is called on the iterator previousIndex() the index of the element that would be returned the next time previous is called on the iterator previous() returns the element before the iterator (throws a NoSuchElementException if there are none) set(value) replaces the element last returned by next or previous with the given value