UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 14.1 Free with a free account
Maps: Pairing Unique Keys With Their Values
Data Structures and Algorithms · Chapter 14: Maps and HashingSection 14.1 · lesson 56 of 878 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Data Structures and Algorithms.
Lesson complete
Earn the 3 college credits for Data Structures and Algorithms
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Hash Functions: Spreading Keys Evenly Across Slots →← Sorting With Priority Queues: Heap SortNext lesson: Hash Functions: Spreading Keys Evenly Across Slots →
In this lesson
Map rules, Java Map methods and why list-based maps are slow.
- State the rules of a map: unique keys, repeatable values and lookup by key
- Predict the return values of put, get, getOrDefault, containsKey and remove
- Analyze why a list-based map costs order n for every operation
- Compare sorted lists and direct-index arrays as alternatives to hashing
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,169 words). Read along, or search it.
Opening Question
Lookups by Identifier
Much of everyday computing is a lookup. Given a product code, what's in stock? Given a username, which profile belongs to it? Given a word, how many times has it appeared? Given a student ID, what's the record? Each time, you hold an identifier and want the information that goes with it. You don't care where in some list it happens to sit.
Definition
Three Rules of a Map
A structure built for this job is a map. It holds entries, and each entry pairs a key with a value. Three rules define it. Keys are unique: putting an existing key replaces the old value. Values may repeat: here, pen and tape both have twelve. And you look things up by key, never by value. The core operations are put, get, remove and contains key, with size and is empty as helpers.
Java Example
What Put, Get and Remove Return
Java offers the map as the Map interface, implemented by HashMap, LinkedHashMap and TreeMap. Two keys are the same when equals says so. Watch what put returns. For a new key, it returns null. For an existing key, it returns the old value it just replaced: twelve. Get returns fifteen for pen, and null for the missing cap. Get or default lets you name a replacement answer instead, here zero. Contains key answers true or false. Remove returns the value it deleted, zero, and a second remove returns null. One entry is left.
Common Trap
Null Values Versus Missing Keys
There's one trap. A HashMap may hold null as a value. After putting x with null, get x and get y both return null. Yet contains key says true for x, and false for y. Whenever null could be a real value, ask contains key to tell missing from present but empty.
Quick Check
Tracing Puts, Removes and Gets
Quick check. An empty HashMap gets put a one, put b two, put a three, then remove a, get a, get or default a nine, and size. The program prints every result on one line. What does it print? Pause and predict. It prints null, null, one, three, null, nine, one. The first two puts add new keys, so they return null. The third put replaces a's value and returns the old one, one. Remove a returns three, so get a then finds nothing, and get or default gives nine. Only b is left, so the size is one. The second option forgets that put returns the replaced value, and the third treats put as returning the new one.
Application
Counting Words in a Map
A map makes word counting short. For each word, get or default returns zero the first time it's seen, so put stores one. A linked hash map keeps the order of first appearance, so the counts print as to two, be two, or one, not one.
Simple Design
A Map Stored as a List
How does a map find the entry for a key quickly? To see why that's hard, here's the plainest possible map: its entries sit in a list. Each entry is a small record holding a key and a value. Every operation starts with the same helper, find, which walks the list from the front until it meets the key. Put replaces the entry if the key exists, and adds one otherwise. Get, contains key and remove all lean on find too. And remove shifts the later entries left. This version also counts every key comparison, so we can measure it.
Cost Analysis
Every Operation Is Order n
Start with four entries: pen, ink, pad and tape. Getting tape takes four checks, because it's fourth. Getting the absent cap also takes four: every entry was checked. Putting cap takes four too. Adding at the end is cheap, but keys are unique, so the map must first check that cap isn't already there. Putting pen takes one check, since pen is first. Removing ink takes two, and then the later entries shift left. As the map grows, the pattern is exact. An absent key costs n checks. A present key costs n plus one, over two, on average, and n at worst. So every operation on a list-based map is order n. Doubling the entries doubles the work.
Measured Results
List Map Versus HashMap Timings
In time, measured on one machine for a thousand lookups: the list-based map took about ten times longer for every tenfold increase in size. It climbed from a hundred fifty-five microseconds at a hundred entries to about a fifth of a second at a hundred thousand. Java's HashMap barely changed: ninety-nine microseconds at a hundred thousand entries, over two thousand times faster. Something in its design avoids checking the entries one by one.
Quick Check
Looking Up an Absent Key
Quick check. A list-based map holds fifty thousand entries. About how many key checks does a lookup need, for a key that isn't in the map? Pause, and decide. Fifty thousand. The search must check every entry before it can give up. About twenty-five thousand is the average for a key that is present. And about sixteen is what binary search on a sorted list would need, which this map can't do.
Rescue Attempts
Sorted Lists and Direct Indexing
Can the list be rescued? Attempt one: keep it sorted by key, and use binary search, which halves the range at every step. Measured on sorted arrays, a search took nine comparisons on average among a thousand keys, and nineteen among a million. A huge improvement for get. But the price moves to put. A new key needs a gap at its position: in a sorted list of a thousand, an insertion moved about five hundred entries on average. And the keys must be of a kind that can be put in order. Attempt two: use the key as an array index. Key three goes in slot three, and every operation is one step. But the array needs a slot for every possible key. Nine-digit student IDs would need a billion slots, about four gigabytes, almost all empty. And words have no slot number at all.
Wish List
The Case for Hashing
Side by side: the unsorted list is order n for everything. The sorted list gets order log n lookups, but order n puts and removes. The array indexed by the key is one step for everything, but needs a slot for every possible key. So the wish list is clear: the one-step speed of an array index, for any kind of key, using space in proportion to the entries actually stored. That idea is called hashing. Hashing computes a slot number straight from the key itself.
Key Takeaways
Unique Keys and Costly Lists
To sum up. A map stores entries, each pairing a unique key with a value. Putting an existing key replaces its value. In Java, put returns the old value, get returns null for a missing key, and contains key tells missing from a stored null. A list-based map is order n for every operation, even adding a new key, because uniqueness must be checked. A sorted list speeds up get but slows put. An array index is fast, but needs a slot for every possible key.
Think About It
Skipping the Uniqueness Check
Something to think about. Suppose a program promises never to add the same key twice, so put could simply add at the end. How fast would put become? What would get still cost? And what risk would the program be taking?
About Data Structures and Algorithms at UPI Study
Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms
Why take it here
Why students take Data Structures and Algorithms with UPI Study
Where the credit goes
Universities that work with NCCRS
Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Maps: Pairing Unique Keys With Their Values
What is a map data structure?
What does put return in a Java HashMap?
How do you tell a missing key from a null value in a Java HashMap?
Why is a map stored as an unsorted list slow?
About the Data Structures and Algorithms course
How many college credits is Data Structures and Algorithms?
How much does Data Structures and Algorithms cost and what is included?
Which universities accept UPI Study credits?
How long does Data Structures and Algorithms take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Data Structures and Algorithms.
87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →