Lecture Objectives  To understand the Java Map and Set interfaces and how to use them  To be introduced to the implementation of Map s and Set s  To.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
Michael Alves, Patrick Dugan, Robert Daniels, Carlos Vicuna
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
Hashing as a Dictionary Implementation
SETS AND MAPS Chapter 7 Common final examinations When: Thursday, 12/12, 3:30-5:30 PM Where: Ritter Hall - Walk Auditorium 131.
Trees Chapter 8.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 21 Generics.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Sets and Maps ITEC200 – Week Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn.
Fall 2007CS 225 Sets and Maps Chapter 9. Fall 2007CS 225 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L16 (Chapter 22) Java Collections.
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.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Sets and Maps (and Hashing)
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Chapter 19 Java Data Structures
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
SETS AND MAPS Chapter 9. Chapter Objectives  To understand the C++ map and set containers and how to use them  To learn about hash coding and its use.
Comp 249 Programming Methodology Chapter 15 Linked Data Structure - Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Trees. Tree Terminology Chapter 8: Trees 2 A tree consists of a collection of elements or nodes, with each node linked to its successors The node at the.
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.
Lecture Objectives To understand the Java Map and Set interfaces and how to use them To be introduced to the implementation of Map s and Set s To see how.
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.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
CS212: DATA STRUCTURES Lecture 10:Hashing 1. Outline 2  Map Abstract Data type  Map Abstract Data type methods  What is hash  Hash tables  Bucket.
Lecture Objectives  To learn how to use a Huffman tree to encode characters using fewer bytes than ASCII or Unicode, resulting in smaller files and reduced.
(c) University of Washington14-1 CSC 143 Java Collections.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
111 © 2002, Cisco Systems, Inc. All rights reserved.
© 2006 Pearson Addison-Wesley. All rights reserved13 B-1 Chapter 13 (continued) Advanced Implementation of Tables.
Chapter 18 Java Collections Framework
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
Chapter 11 B Trees. © 2004 Pearson Addison-Wesley. All rights reserved 11 B-2 The ADT Binary Search Tree A deficiency of the ADT binary tree which is.
SETS AND MAPS Chapter 7. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Priority Queues. Priority Queue ADT A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the Priority Queue.
AD Lecture #3 Java Collection Framework 1.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
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.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
Chapter 11. Chapter Summary  Introduction to trees (11.1)  Application of trees (11.2)  Tree traversal (11.3)  Spanning trees (11.4)
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Sets and Maps Chapter 9.
Chapter 19 Java Data Structures
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Road Map CS Concepts Data Structures Java Language Java Collections
Sets and Maps Chapter 7.
Heaps and Priority Queues
Sets and Maps Chapter 9.
Presentation transcript:

Lecture Objectives  To understand the Java Map and Set interfaces and how to use them  To be introduced to the implementation of Map s and Set s  To see how two earlier applications can be implemented more easily using Map objects for data storage CS340 1

Introduction  We learned about part of the Java Collection Framework in Chapter 2 ( ArrayList and LinkedList )  The classes that implement the List interface are all indexed collections  An index or subscript is associated with each element  The element's index often reflects the relative order of its insertion in the list  Searching for a particular value in a list is generally O(n)  An exception is a binary search of a sorted object, which is O(log n) CS340 2

Introduction (cont.)  In this chapter, we consider another part of the Collection hierarchy: the Set interface and the classes that implement it  Set objects  are not indexed  do not reveal the order of insertion of items  enable efficient search and retrieval of information  allow removal of elements without moving other elements around CS340 3

Introduction (cont.)  Relative to a Set, Map objects provide efficient search and retrieval of entries that contain pairs of objects (a unique key and the information)  Hash tables (implemented by a Map or Set ) store objects at arbitrary locations and offer an average constant time for insertion, removal, and searching CS340 4

Section 7.1 Sets and the Set Interface 5 CS340

Sets and the Set Interface CS340 6

The Set Abstraction  A set is a collection that contains no duplicate elements and at most one null element  adding "apples" to the set {"apples", "oranges", "pineapples"} results in the same set (no change)  Operations on sets include:  testing for membership  adding elements  removing elements  unionA ∪ B  intersectionA ∩ B  differenceA – B  subsetA ⊂ B CS340 7

The Set Abstraction(cont.)  The union of two sets A, B is a set whose elements belong either to A or B or to both A and B. Example: {1, 3, 5, 7} ∪ {2, 3, 4, 5} is {1, 2, 3, 4, 5, 7}  The intersection of sets A, B is the set whose elements belong to both A and B. Example: {1, 3, 5, 7} ∩ {2, 3, 4, 5} is {3, 5}  The difference of sets A, B is the set whose elements belong to A but not to B. Examples: {1, 3, 5, 7} – {2, 3, 4, 5} is {1, 7}; {2, 3, 4, 5} – {1, 3, 5, 7} is {2, 4}  Set A is a subset of set B if every element of set A is also an element of set B. Example: {1, 3, 5, 7} ⊂ {1, 2, 3, 4, 5, 7} is true CS340 8

The Set Interface and Methods  Required methods: testing set membership, testing for an empty set, determining set size, and creating an iterator over the set  Optional methods: adding an element and removing an element  Constructors to enforce the “no duplicate members” criterion  The add method does not allow duplicate items to be inserted CS340 9

The Set Interface and Methods(cont.)  Required method: containsAll tests the subset relationship  Optional methods: addAll, retainAll, and removeAll perform union, intersection, and difference, respectively CS340 10

The Set Interface and Methods(cont.) Ann Sally Jill setA Ann Bob Jill setB Bill CS340 11

The Set Interface and Methods(cont.) Ann Sally Jill setA Ann Bob Jill setB Bill setA.addAll(setB); CS340 12

The Set Interface and Methods(cont.) Ann Sally Jill setA Ann Bob Jill setB Bill setA.addAll(setB); System.out.println(setA); Outputs: [Bill, Jill, Ann, Sally, Bob] CS340 13

The Set Interface and Methods(cont.) Ann Sally Jill setA Ann Bob Jill setB Bill If a copy of original setA is in setACopy, then... CS340 14

The Set Interface and Methods(cont.) Ann Sally Jill setA Ann Bob Jill setB Bill setACopy.retainAll(setB); CS340 15

The Set Interface and Methods(cont.) Ann Sally Jill setA Ann Bob Jill setB Bill setACopy.retainAll(setB); System.out.println(setACopy); Outputs: [Jill, Ann] CS340 16

The Set Interface and Methods(cont.) Ann Sally Jill setA Ann Bob Jill setB Bill setACopy.removeAll(setB); System.out.println(setACopy); Outputs: [Sally] CS340 17

Comparison of Lists and Sets  Collections implementing the Set interface must contain unique elements  Unlike the List.add method, the Set.add method returns false if you attempt to insert a duplicate item  Unlike a List, a Set does not have a get method—elements cannot be accessed by index CS340 18

Comparison of Lists and Sets (cont.)  You can iterate through all elements in a Set using an Iterator object, but the elements will be accessed in arbitrary order for (String nextItem : setA) { //Do something with nextItem … } CS340 19

Section 7.2 Maps and the Map Interface 20 CS340

Maps and the Map Interface  The Map is related to the Set  Mathematically, a Map is a set of ordered pairs whose elements are known as the key and the value  Keys must be unique, but values need not be unique  You can think of each key as a “mapping” to a particular value  A map provides efficient storage and retrieval of information in a table  A map can have many-to-one mapping: ( B, Bill ), ( B2, Bill ) {(J, Jane), (B, Bill), (S, Sam), (B1, Bob), (B2, Bill)} CS340 21

Maps and the Map Interface(cont.)  In an onto mapping, all the elements of valueSet have a corresponding member in keySet  The Map interface should have methods of the form V.get (Object key) V.put (K key, V value) CS340 22

Maps and the Map Interface(cont.)  When information about an item is stored in a table, the information should have a unique ID  A unique ID may or may not be a number  This unique ID is equivalent to a key Type of itemKeyValue University studentStudent ID numberStudent name, address, major, grade point average Online store customer addressCustomer name, address, credit card information, shopping cart Inventory itemPart IDDescription, quantity, manufacturer, cost, price CS340 23

Map Hierarchy CS340 24

Map Interface CS340 25

Map Interface (cont.)  The following statements build a Map object: Map aMap = new HashMap (); aMap.put("J", "Jane"); aMap.put("B", "Bill"); aMap.put("S", "Sam"); aMap.put("B1", "Bob"); aMap.put("B2", "Bill"); J S B1 B B2 Jane Sam Bob Bill CS340 26

Map Interface (cont.) aMap.get("B1") returns: "Bob" J S B1 B B2 Jane Sam Bob Bill CS340 27

Map Interface (cont.) aMap.get("Bill") returns: null (" Bill " is a value, not a key) J S B1 B B2 Jane Sam Bob Bill CS340 28

Creating an Index of Words  In Section 6.4 we used a binary search tree to store an index of words occurring in a term paper  Each element in the binary search tree consisted of a word followed by a three digit line number  If we store the index in a Map, we can store all the line number occurrences for a word in a single index entry CS340 29

Creating an Index of Words (cont.)  Each time a word is encountered, its list of line numbers is retrieved (using the word as key)  The most recent line number is appended to this list CS340 30

Creating an Index of Words (cont.)  Listing 7.2 (Method buildIndexAllLines ; page 371) CS340 31

Section 7.6 Additional Applications of Maps

Cell Phone Contact List (cont.)  Analysis  A map will associate the name (the key) with a list of phone numbers (value)  Implement ContactListInterface by using a Map > object for the data type

Cell Phone Contact List (cont.)  Design public class MapContactList implements ContactListInterface { Map > contacts = new TreeMap >();... }

Cell Phone Contact List (cont.)  Implementation: writing the required methods using the Map methods is straightforward

Huffman Coding  Problem  Build an array of (weight, symbol) pairs, where weight is the frequency of occurrence of each symbol for any data file  Encode each symbol in the input file by writing the corresponding bit string for that symbol to the output file

Huffman Coding (cont.)  Analysis  For each task in the problem, we need to look up a symbol in a table  Using a Map ensures that the lookup is expected O(1)  For the frequency table, the symbol will be the key, and the value will be the count of its occurrences  We can construct a Huffman tree using a priority queue (Section 6.6)  Then we build a code table that stores the bit string code (obtained from a preorder traversal of the Huffman tree) associated with each symbol

Huffman Coding (cont.)  Design Algorithm for buildFreqTable 1. while there are more characters in the input file 2. Read a character and retrieve its corresponding entry in frequencies. 3. if the value field is null 4. Set value to else 6. Increment value. 7. Create a set view of frequencies. 8. for each entry in the set view 9. Store its data as a weight-symbol pair in the HuffData array. 10. Return the HuffData array.

Huffman Coding (cont.) Algorithm for Method buildCodeTable 1. Get the data at the current root. 2. if a symbol is stored in the current root (reached a leaf node) 3. insert the symbol and bit string code so far as a new code table entry. 4. else 5. append a 0 to the bit string code so far. 6. apply the method recursively to the left subtree. 7. append a 1 to the bit string code. 8. apply the method recursively to the right subtree.

Huffman Coding (cont.) Algorithm for Method encode 1. while there are more characters in the input file 2. read a character and get its corresponding bit string code. 3. write its bit string to the output file.

Huffman Coding (cont.)  Listing 7.12 (Method buildFreqTable ; pages )

Huffman Coding (cont.)  Testing  Download class BitString and write a main method that calls the methods in the proper sequence  For interim testing, read a data file and display the frequency table to verify its correctness  Use StringBuffer or StringBuilder instead of BitString to build a code of characters (' 0 ' or ' 1 ') instead of bits; verify its correctness

Section 7.7 Navigable Sets and Maps

SortedSet and SortedMap  Java 5.0's SortedSet interface extends Set by providing the user with an ordered view of the elements with the ordering defined by a compareTo method  Because the elements are ordered, additional methods can return the first and last elements and define subsets  The ability to define subsets was limited because subsets always had to include the starting element and exclude the ending element  SortedMap interface provides an ordered view of a map with elements ordered by key value

NavigableSet and NavigableMap  Java 6 added NavigableSet and NavigableMap interfaces as extensions to SortedSet and SortedMap  Java retains SortedSet and SortedMap for compatibility with existing software  The new interfaces allow the user to specify whether the start or end items are included or excluded  They also enable the user to specify a subset or submap that is traversable in the reverse order

NavigableSet Interface (cont.) Listing 7.13 illustrates the use of a NavigableSet. The output of this program consists of the lines: The original set odds is [1, 3, 5, 7, 9] The ordered set b is [3, 5, 7] Its first element is 3 Its smallest element >= 6 is 7

NavigableMap Interface

Application of a NavigableMap Interface  computeAverage computes the average of the values defined in a Map  computeSpans creates a group of submaps of a NavigableMap and passes each submap to computeAverage  Given a NavigableMap in which the keys represent years and the values are some statistics for the year, we can generate a table of averages covering different periods

Application of a NavigableMap Interface (cont.)  Example: Given a map of tropical storms representing the number of tropical storms from 1960 through 1969 List stormAverage = computeSpans(storms,2) Calculates the average number of tropical storms for each successive pair of years

Method computeAverage /** Returns the average of the numbers in its Map valueMap The map whose values are The average of the map values */ Public static double computeAverage(Map valueMap){ int count = 0; double sum = 0; for(Map.Entry entry : valueMap.entrySet()) { sum += entry.getValue().doubleValue(); count++; } return (double) sum / count;

Method computeSpans /** Return a list of the averages of nonoverlapping spans of values in its NavigableMap valueMap The map whose values are delta The number of map values in each An ArrayList of average values for each span */ Public static List computeSpans(NavigableMap valueMap, int delta) { List result = new ArrayList (); Integer min = (Integer) valueMap.firstEntry().getKey(); Integer max = (Integer) valueMap.lastEntry().getKey(); for (int index = min; index <= max; index += delta) { double average = computeAverage(valueMap.subMap(index, true, index+delta, false)); result.add(average); } return result; }