Chapter 13 Sets and Maps Modified. Chapter Scope The Java API set and map collections Using sets and maps to solve problems How the Java API implements.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Hash Tables,
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Chapter 7 Iterators Modified. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using.
CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Chapter 13 Linked Structures - Stacks. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked implementation.
Chapter 22 Sets and Maps. Chapter Scope The Java API set and map collections Using sets and maps to solve problems How the Java API implements sets and.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Chapter 19 Java Data Structures
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Recitation 1 CS0445 Data Structures Mehmud Abliz.
1 Sets and Maps Starring: keySet Co-Starring: Collections.
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
Big Java Chapter 16.
Chapter 9 Searching and Sorting
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Chapter 18 Java Collections Framework
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
Collection 105 Yola. To store data in RAM Variables (name all the types with their length) Arrays (one, two or more) Collections and Maps.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
SETS AND MAPS Collections of Data. Advanced Data Structures Often referred to as the Java Collections Framework…. Set and map data types Hash tables Binary.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
Sets and Maps Sets Maps The Comparator Interface Sets and Maps in Java Collections API – TreeSet – TreeMap Review for Exam Reading:
9-1 9 Set ADTs Set concepts. Set applications. A set ADT: requirements, contract. Implementations of sets: using arrays, linked lists, boolean arrays.
13 Collections Framework. 2 Contents What is Collection? Collections Framework Collections Hierarchy Collections Implementations Set List Map.
Maps Nick Mouriski.
Week 9 - Friday.  What did we talk about last time?  Collisions  Open addressing ▪ Linear probing ▪ Quadratic probing ▪ Double hashing  Chaining.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
For Friday Finish reading chapter 9 WebCT quiz 17.
Iterators. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using iterators to solve.
A 2-D Array is a structure that storage space both vertically and horizontally. Thus, the array has both rows and columns. 2-D Arrays are used to create.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Appendix I Hashing.
Sixth Lecture ArrayList Abstract Class and Interface
Ch 16: Data Structures - Set and Map
Efficiency of in Binary Trees
Data Structures TreeMap HashMap.
Computer Programming Methodology Input and While Loop
Chapter 4 Linked Structures - Stacks
Road Map CS Concepts Data Structures Java Language Java Collections
TreeSet TreeMap HashMap
Chapter 7 Iterators.
Java Software Structures: John Lewis & Joseph Chase
Chapter 4 Linked Structures - Stacks
CSE 373: Data Structures and Algorithms
CSE 373 Data Structures and Algorithms
CSE 373: Data Structures and Algorithms
Recursive Objects Singly Linked Lists.
Presentation transcript:

Chapter 13 Sets and Maps Modified

Chapter Scope The Java API set and map collections Using sets and maps to solve problems How the Java API implements sets and maps Hashing Java Software Structures, 4th Edition, Lewis/Chase

Sets A set is a collection of elements with no duplicates No other relationship among the elements should be assumed A primary purpose of a set is to determine whether a particular element is a member Other collections (such as lists) can test for containment, but if that operation is important, consider using sets Java Software Structures, 4th Edition, Lewis/Chase

xxx Operations on a set:

Sets Operations on a set, continued: Java Software Structures, 4th Edition, Lewis/Chase

Maps A map is a collection that establishes a relationship between keys and values The goal is to have an efficient way of obtaining a value given its key Keys of a map must be unique, but multiple keys could map to the same object For example, a membership id (a String ) could be the key used to retrieve a member (a Member object) Java Software Structures, 4th Edition, Lewis/Chase

Maps Operations on a map:

Maps Operations on a map, continued: Java Software Structures, 4th Edition, Lewis/Chase

Using Sets Let's use a set to test for containment In particular, we'll create a set of web domains that will be blocked The blocked domains will be held in an input file The set is represented using a TreeSet object from the Java API Java Software Structures, 4th Edition, Lewis/Chase

import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.TreeSet; /** A URL domain blocker. */ public class DomainBlocker { private TreeSet blockedSet; /** Sets up the domain blocker by reading in the blocked domain names from * a file and storing them in a TreeSet. FileNotFoundException */ public DomainBlocker() throws FileNotFoundException { blockedSet = new TreeSet (); File inputFile = new File("blockedDomains.txt"); Scanner scan = new Scanner(inputFile); while (scan.hasNextLine()) { blockedSet.add(scan.nextLine()); } Java Software Structures, 4th Edition, Lewis/Chase

/** * Checks to see if the specified domain has been blocked. * domain the domain to be checked true if the domain is blocked and false otherwise */ public boolean domainIsBlocked(String domain) { return blockedSet.contains(domain); } Java Software Structures, 4th Edition, Lewis/Chase

import java.io.FileNotFoundException; import java.util.Scanner; /** Domain checking driver. */ public class DomainChecker { /** * Repeatedly reads a domain interactively from the user and * checks to see if that domain has been blocked. */ public static void main(String[] args) throws FileNotFoundException { DomainBlocker blocker = new DomainBlocker(); Scanner scan = new Scanner(System.in); String domain; Java Software Structures, 4th Edition, Lewis/Chase

do { System.out.print("Enter a domain (DONE to quit): "); domain = scan.nextLine(); if (!domain.equalsIgnoreCase("DONE")) { if (blocker.domainIsBlocked(domain)) System.out.println("That domain is blocked."); else System.out.println("That domain is fine."); } } while (!domain.equalsIgnoreCase("DONE")); } Java Software Structures, 4th Edition, Lewis/Chase

Using Maps Now let's look at an example using maps to keep track of product sales Suppose that each time a product is sold, its product code is entered into a sales file Our example will read the sales file and update product sales summary A TreeMap will be used to map the product code to the Product object Java Software Structures, 4th Edition, Lewis/Chase

/** Represents a product for sale. */ public class Product implements Comparable { private String productCode; private int salesCount; // Number of items sold /** * Creates the product with the specified code. * productCode a unique code for this product */ public Product(String productCode) { this.productCode = productCode; this.salesCount = 0; } Java Software Structures, 4th Edition, Lewis/Chase

/** * Returns the product code for this product. * the product code */ public String getProductCode() { return productCode; } /** * Increments the sales of this product. */ public void incrementSales() { salesCount++; } Java Software Structures, 4th Edition, Lewis/Chase

/** * Compares this product to the specified product based on the * product code. other the other product an integer code result */ public int compareTo(Product obj) { return productCode.compareTo(obj.getProductCode()); } /** * Returns a string representation of this product. * a string representation of the product */ public String toString() { return productCode + "\t(" + salesCount + ")"; } Java Software Structures, 4th Edition, Lewis/Chase

import java.io.File; import java.io.IOException; import java.util.Scanner; import java.util.TreeMap; /** Demonstrates the use of a TreeMap to store a sorted group * of Product objects. */ public class ProductSales { /** Processes product sales data and prints a summary sorted by * product code. */ public static void main(String[] args) throws IOException {// Construct a map for product data – key is product code TreeMap sales = new TreeMap (); // Read product code for each sale transaction Scanner scan = new Scanner(new File("salesData.txt")); String code; Product product; Java Software Structures, 4th Edition, Lewis/Chase

while (scan.hasNext()) { code = scan.nextLine(); product = sales.get(code); if (product == null) // Product not in map yet sales.put(code, new Product(code)); else // Product is in map product.incrementSales(); } // Print out product info for all products in map System.out.println("Products sold this period:"); for (Product prod : sales.values()) System.out.println(prod); } Java Software Structures, 4th Edition, Lewis/Chase

Using Maps Another example using maps, stores user information which can be retrieved by a user id This time, a HashMap is used to store the users Java Software Structures, 4th Edition, Lewis/Chase

/** Represents a user with a userid. */ public class User { private String userId; private String firstName; private String lastName; /** * Sets up this user with the specified information. * userId a user identification string firstName the user's first name lastName the user's last name */ public User(String userId, String firstName, String lastName) { this.userId = userId; this.firstName = firstName; this.lastName = lastName; } Java Software Structures, 4th Edition, Lewis/Chase

/** Returns the user id of this user. */ public String getUserId() { return userId; } /** Returns a string representation of this user. */ public String toString() { return userId + ":\t" + lastName + ", " + firstName; } Java Software Structures, 4th Edition, Lewis/Chase

import java.util.HashMap; import java.util.Set; /** Stores and manages a map of users. */ public class Users { // A hashmap to store users private HashMap userMap; /** Creates a user map to track users. */ public Users() { userMap = new HashMap (); } /** Adds a new user to the user map. */ public void addUser(User user) { userMap.put(user.getUserId(), user); } Java Software Structures, 4th Edition, Lewis/Chase

/** Retrieves and returns the specified user. */ public User getUser(String userId) { return userMap.get(userId); } /** Returns a set of all user ids. */ public Set getUserIds() { return userMap.keySet(); } Java Software Structures, 4th Edition, Lewis/Chase

import java.io.IOException; import java.util.Scanner; /** Demonstrates the use of a map to manage a set of objects. */ public class UserManagement { /** Creates and populates a group of users. Then prompts for * interactive searches, and finally prints all users. */ public static void main(String[] args) throws IOException { // Construct and populate a new instance of users Users users = new Users(); users.addUser(new User("fziffle", "Fred", "Ziffle")); users.addUser(new User("geoman57", "Marco", "Kane")); users.addUser(new User("rover322", "Kathy", "Shear")); users.addUser(new User("appleseed", "Sam", "Geary")); users.addUser(new User("mon2016", "Monica", "Blankenship")); Scanner scan = new Scanner(System.in); String uid; User user; Java Software Structures, 4th Edition, Lewis/Chase

do { // Read a uid from keyboard System.out.print("Enter User Id (DONE to quit): "); uid = scan.nextLine(); if (!uid.equalsIgnoreCase("DONE")) { user = users.getUser(uid); if (user == null) // uid not found as a key System.out.println("User not found."); else // uid used to retrieve user info System.out.println(user); } } while (!uid.equalsIgnoreCase("DONE")); // print all info for all users System.out.println("\nAll Users:\n"); for (String userId : users.getUserIds()) System.out.println(users.getUser(userId)); } Java Software Structures, 4th Edition, Lewis/Chase

Implementing Sets and Maps The TreeSet and TreeMap classes use an underlying tree to hold the elements of the set or map These trees are binary search trees, and in particular are red-black balanced trees All of the basic operations are performed with O(log n) efficiency Java Software Structures, 4th Edition, Lewis/Chase

Implementing Sets and Maps The HashSet and HashMap classes are implemented using a technique called hashing An element in a hash table is stored in a location based on a hash function A hash function makes some calculation based on the element itself Multiple elements may hash to the same location (which is called a collision) A function that maps each element to a unique location is called a perfect hashing function Java Software Structures, 4th Edition, Lewis/Chase

Hashing A hash table with a simple hash function based on the first letter of the string: Collisions could be managed using a list of A names, a list of B names, etc Java Software Structures, 4th Edition, Lewis/Chase