Download presentation
Presentation is loading. Please wait.
Published byEvelyn Manning Modified over 9 years ago
1
ADSA: Maps/9 1 241-423 Advanced Data Structures and Algorithms Objectives – –examples of maps, and introduce map collection views Semester 2, 2013-2014 9. Maps
2
ADSA: Maps/9 2 Contents 1. What is a Map? 2. Map Interfaces 3. The TreeMap Collection 4. Map Collection Views 5. Create a Concordance
3
ADSA: Maps/9 3 1. What is a Map? A map stores data in key ‑ value pairs. A key acts like an index to locate the corresponding value in the map – –a map is also called an associative array
4
ADSA: Maps/9 4 2. The Map Hierarchy The dashed lines indicate that the class implements the interface. The Map interface is separate from the Collection hierarchy, since if defines methods not relevant to general collections.
5
ADSA: Maps/9 5 The Map Interface V K K K
6
ADSA: Maps/9 6 size(), isEmpty(), and clear() are like those in the Collection interface. A map does not have an iterator to scan its elements – –instead, keySet() and entrySet() return the keys and the entries in a map as a set (see later)
7
ADSA: Maps/9 7 3. The TreeMap Collection TreeMap is an ordered collection that accesses elements in ascending order of its keys. The class implements the OrderedMap interface (see slide 3) – –firstKey() and lastKey() return the values corresponding to the minimum and maximum keys
8
ADSA: Maps/9 8 V V
9
9 Brief TreeMap Example // arrays for class names and their enrollment (student nos) String[] className = {"ECON 101","CS 173","ENGL 25"}; int[] enrollment = {85, 14, 30}; // create a TreeMap object TreeMap tm = new TreeMap (); for(int i = 0; i < 3; i++) tm.put(className[i], enrollment[i]);
10
ADSA: Maps/9 10 3.1. Student Working Hours Map import java.util.Scanner; import java.io.FileReader; import java.io.FileNotFoundException; import ds.util.TreeMap; import ds.time.Time24; public class CalcHours { public static void main(String[] args) { TreeMap workMap = new TreeMap (); : the key-value pair is student name and hours worked
11
ADSA: Maps/9 11 /* access the student info file: each line consists of a student name and their work time in hours and mins */ Scanner fin = null; try { // load student info fin = new Scanner(new FileReader("studwk.txt")); } catch (FileNotFoundException e) { System.err.println("Cannot open "\"studwk.txt""); System.exit(1); } :
12
ADSA: Maps/9 12 // input names and times while (fin.hasNext()) { String studName = fin.next(); // get hours and minutes from the input line int hours = fin.nextInt(); int mins = fin.nextInt(); Time24 workTime = new Time24(hours,mins); // access entry for the student name Time24 timeValue = workMap.get(studName); :
13
ADSA: Maps/9 13 if (timeValue == null) // add new entry workMap.put(studName, workTime); else { // update existing entry timeValue.addTime(hours*60 + mins); workMap.put(studName, timeValue); } // display the work Map System.out.println("Student-Time: " + workMap); } // end of main() } // end of CalcHours class
14
ADSA: Maps/9 14 Execution
15
ADSA: Maps/9 15 3.2. A Software Map import java.io.FileReader; import java.io.FileNotFoundException; import java.util.Scanner; import ds.util.TreeMap; import ds.util.TreeSet; public class MakeSoftMap { public static void main(String[] args) { TreeMap > softwareMap = new TreeMap >(); : the key-value pair is company name and a set of software names
16
ADSA: Maps/9 16 /* access the product info file: each line consists of a company name and software product name, separated by a tab */ Scanner fin = null; try { // load product info fin = new Scanner(new FileReader("product.txt")); fin.useDelimiter("[\t\n\r]+"); } catch (FileNotFoundException e){ System.err.println("Cannot open "\"product.txt\""); System.exit(1); } :
17
ADSA: Maps/9 17 while(fin.hasNext()){ String company = fin.next(); String product = fin.next(); // look for software set for the company TreeSet prodSet = softwareMap.get(company); // if no entry found, then create empty software set if (prodSet == null) prodSet = new TreeSet (); prodSet.add(product); // add product name to set softwareMap.put(company, prodSet); // add entry } // display contents of software Map System.out.println(softwareMap); } // end of main() } // end of MakeSoftMap class
18
ADSA: Maps/9 18 Execution
19
ADSA: Maps/9 19 4. Map Collection Views A map does not have an iterator for accessing its elements. Instead we can use two collection views, which are sets that act on the original map – –the keySet collection view – –the entrySet collection view The original map is sometimes called the backing collection.
20
ADSA: Maps/9 20 In Map, keySet() returns a set of map keys. This set is a collection view for the map. Set keys = peopleMap.keySet(); 4.1. The keySet Collection View
21
ADSA: Maps/9 21 Deletion Deleting a key from the set removes the corresponding entry from the map.
22
ADSA: Maps/9 22 The Set interface defines an add() operation, but this makes no sense for a keySet view: – –add() would have to add a key-value pair to the backing collection, but what value should be added? – –Instead add() throws an UnsupportedOperationException in a keySet view Insertion
23
ADSA: Maps/9 23 4.2. The entrySet Collection View In Map, entrySet() returns a view called an entry set, is a set of key-value entries. The entries implement the Map.Entry interface – –an interface inside the Map interface Set > entriesSet = peopleMap.entrySet();
24
ADSA: Maps/9 24 entriesSet is a set of Map.Entry objects from the peopleMap. Operations on the set affect the map.
25
ADSA: Maps/9 25 confTimeMap holds conference activities and their times. TreeMap confTimeMap = new TreeMap (); confTimeMap.put("Session 1", new Time24(9,30)); confTimeMap.put("Session 2", new Time24(14,00)); confTimeMap.put("Lunch", new Time24(12,0)); confTimeMap.put("Dinner", new Time24(17,30)); Entry Set View Example confTimeMap
26
ADSA: Maps/9 26 // create an entry set for confTimeMap Set > entries = confTimeMap.entrySet(); entries set
27
ADSA: Maps/9 27 4.3. Scanning a Map's Entries A Map.Entry set can be used to define an iterator for scanning the map entries. The iterator can access an entry's key and access/update an entry's value. The iterator remove() method removes an entry from the map
28
ADSA: Maps/9 28 Entry Set Iterators An entry set iterator provides a way to scan the entries in a map. The iterator references a Map.Entry element in the map – –the programmer can use Map.Entry methods to access the map components
29
ADSA: Maps/9 29 // create an entry set for confTimeMap Set > entries = confTimeMap.entrySet(); // create an iterator for the entry set Iterator > iter = entries.iterator(); Examples entries set iter iterator continued
30
ADSA: Maps/9 30 map entries set entries iterator changes will affect original map
31
ADSA: Maps/9 31 Delay all activities by 30 minutes. // scan map entries while (iter.hasNext()) { Map.Entry me = iter.next(); // get next Map.Entry object Time24 t = me.getValue(); t.addTime(30); // add 30 mins me.setValue(t); // update map entry }
32
ADSA: Maps/9 32 for (Map.Entry i : entries) { String activity = (String)i.getKey(); if (activity.indexOf("Session") != -1) //is activity a session? System.out.println("Activity " + activity + " Starting time " + i.getValue()); } Activity Session 1 Starting time 10:00 Activity Session 2 Starting time 14:30 List session starting time.
33
ADSA: Maps/9 33 5. Create a Concordance A concordance is a list of all the unique words from a file along with the line numbers where the words appear. We implement the concordance as a TreeMap.
34
ADSA: Maps/9 34 Input File
35
ADSA: Maps/9 35 Execution
36
ADSA: Maps/9 36 import java.io.*; import java.util.regex.*; import java.util.StringTokenizer; import java.util.Scanner; import ds.util.*; public class CreateConcordance { private static Pattern identifierPattern = Pattern.compile("[a-zA-Z][a-zA-Z0-9]*"); public static void main(String[] args) throws IOException { System.out.print("Enter the file name: "); Scanner keyIn = new Scanner(System.in); String filename = keyIn.nextLine(); System.out.println(); concordance(filename); // create concordance } // end of main()
37
ADSA: Maps/9 37 public static void concordance(String filename) throws IOException { // create the concordance treemap TreeMap > concordanceMap = new TreeMap >(); // create scanner to input from document file Scanner fin = new Scanner(new FileReader(filename)); : the key-value pair is identifier name and a set of line numbers
38
ADSA: Maps/9 38 // read the file a line at a time int lineNumber = 0; while(fin.hasNext()) { String inputLine = fin.nextLine(); // read a line lineNumber++; // create matcher to find identifiers in line Matcher matcher = identifierPattern.matcher(inputLine); // extract identifiers until end of line while (matcher.find()) { String ident = inputLine.substring( matcher.start(), matcher.end()); :
39
ADSA: Maps/9 39 // find line number set for the identifier TreeSet lineNums = concordanceMap.get(ident); if (lineNums == null) // no set; make one lineNums = new TreeSet (); // add line number to set lineNums.add(lineNumber); concordanceMap.put(ident, lineNums); } // output the concordance writeConcordance(concordanceMap); } // end of concordance()
40
ADSA: Maps/9 40 public static void writeConcordance( TreeMap > map) { // create entry view for the map Set >> entries = map.entrySet(); // create iterator over the entry view Iterator >> iter = entries.iterator(); while (iter.hasNext()) { Map.Entry > e = iter.next(); System.out.print( e.getKey() ); // output key // pad output to 12 characters using blanks if (e.getKey().length() < 12) for (int i=0;i < 12 - (e.getKey().length()); i++) System.out.print(' '); :
41
ADSA: Maps/9 41 // extract map value as a TreeSet TreeSet lineNumberSet = e.getValue(); // display identifier and line numbers System.out.print(formatInt(4, lineNumberSet.size()) + ": "); // iterate over TreeSet of line numbers Iterator setIter = lineNumberSet.iterator(); while (setIter.hasNext()) System.out.print( setIter.next() + " "); System.out.println(); } System.out.println(); }
42
ADSA: Maps/9 42 private static String formatInt(int w, int n) /* returns a formatted string with integer n right-justified in a field of w spaces; used to line up output in concordance */ {... } } // end of CreateConcordance class
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.