• Tidak ada hasil yang ditemukan

PPT Slide 1

N/A
N/A
Protected

Academic year: 2023

Membagikan "PPT Slide 1"

Copied!
78
0
0

Teks penuh

(1)

Data Structures for Java Data Structures for Java

William H. Ford William H. Ford William R. Topp William R. Topp

Chapter 19 Chapter 19

Sets and Maps Sets and Maps

Bret Ford

© 2005, Prentice Hall

(2)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Set Collection Set Collection

 A Set implements the Collection interface A Set implements the Collection interface and requires that each element be unique.

and requires that each element be unique.

(3)

Map Map

 A map stores an element as a A map stores an element as a key-value key-value pair pair . In a pair, the first field is the key . In a pair, the first field is the key

which is an attribute that uniquely which is an attribute that uniquely

identifies the element. The second field is identifies the element. The second field is

the value which is an object associated the value which is an object associated

with the key.

with the key.

(4)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Map (continued) Map (continued)

 The figure illustrates a map that might The figure illustrates a map that might be used for university administration.

be used for university administration.

The map is a collection of String-Integer The map is a collection of String-Integer pairs to denote the number of majors in pairs to denote the number of majors in

each of its degree programs. The name of each of its degree programs. The name of

the degree program is the key and the the degree program is the key and the

number of majors is the value

number of majors is the value

(5)

Map (continued) Map (continued)

 A map collection uses the key to access A map collection uses the key to access the value field of the entry. For instance, the value field of the entry. For instance,

assume degreeMap is the map collection assume degreeMap is the map collection

for departments and major counts. The for departments and major counts. The

operation degreeMap.get("English") operation degreeMap.get("English")

returns the Integer component with value returns the Integer component with value

117, which identifies the number of 117, which identifies the number of

English majors.

English majors.

(6)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Map (concluded) Map (concluded)

 The Set interface extends the Collection The Set interface extends the Collection interface, but the Map interface is

interface, but the Map interface is

separate, since if defines methods not separate, since if defines methods not

relevant to general collections.

relevant to general collections.

(7)

Set and Map Interfaces Set and Map Interfaces

The interfaces and collection classes The interfaces and collection classes

that define sets and maps. The dashed lines that define sets and maps. The dashed lines

indicate that the class implements the indicate that the class implements the

interface.

interface.

(8)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

TreeSet Collection TreeSet Collection

 TreeSet is implemented by a binary search TreeSet is implemented by a binary search tree. As a result, it implements the

tree. As a result, it implements the

OrderedSet interface that extends the Set OrderedSet interface that extends the Set

interface and defines the methods first() interface and defines the methods first()

and last().

and last().

(9)

TreeSet Collection TreeSet Collection

(concluded)

(concluded)

(10)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Spell Checker Spell Checker

 A set is an ideal structure for the A set is an ideal structure for the

implementation of a simple spelling implementation of a simple spelling

checker.

checker.

The file "dict.dat" is a set of strings containing The file "dict.dat" is a set of strings containing approximately 25,000 words in lower case.

approximately 25,000 words in lower case.

Open the file using the Scanner class.

Open the file using the Scanner class.

For each word, call contains() to determine For each word, call contains() to determine whether the word is in the dictionary set. If whether the word is in the dictionary set. If

not, assume the word is misspelled and not, assume the word is misspelled and

interact with the user for instructions on how interact with the user for instructions on how

to proceed.

to proceed.

(11)

spellChecker() spellChecker()

public static void spellChecker(

String filename) {

// sets storing the dictionary and the // misspelled words

TreeSet<String> dictionary = new TreeSet<String>(), misspelledWords = new TreeSet<String>();

Scanner dictFile = null, docFile = null;

// create Scanner objects to input dictionary // and document

try {

// dictionary and document streams

dictFile = new Scanner(new FileReader("dict.dat"));

docFile = new Scanner(new FileReader(filename));

}

(12)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

spellChecker() (continued) spellChecker() (continued)

catch(FileNotFoundException fnfe) {

System.err.println("Cannot open a file");

System.exit(1);

}

// string containing each word from the // dictionary and from the document

String word;

// user response when a misspelled word is noted String response;

// insert each word from file "dict.dat" into a set while(dictFile.hasNext())

{

// input next word and add to dictionary word = dictFile.next();

dictionary.add(word);

}

(13)

spellChecker() (continued) spellChecker() (continued)

// read the document word by word and check spelling while(docFile.hasNext())

{

// get the next word from the document word = docFile.next();

// look word up in the dictionary; if not // present assume word is misspelled; prompt // user to add word to the dictionary, ignore // it, or flag as misspelled

if (!dictionary.contains(word)) {

System.out.println(word);

System.out.print(

" 'a'(add) 'i'(ignore) " + "'m'(misspelled) ");

response = keyIn.next();

(14)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

spellChecker() (concluded) spellChecker() (concluded)

// if response is 'a' add to dictionary;

// if not ignored, add to set of // misspelled words

if (response.charAt(0) == 'a') dictionary.add(word);

else if (response.charAt(0) == 'm') misspelledWords.add(word);

} }

// display the set of misspelled words

System.out.println("\nMisspelled words: " + misspelledWords);

}

(15)

Program 19.1 Program 19.1

import java.io.FileReader;

import java.io.FileNotFoundException;

import java.util.Scanner;

import ds.util.TreeSet;

public class Program19_1 {

// keyboard input stream used by main() // and spellChecker()

static Scanner keyIn = new Scanner(System.in);

public static void main(String[] args) {

String fileName;

// enter the file name for the document

System.out.print("Enter the document to " + "spell check: ");

fileName = keyIn.next();

(16)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.1 (concluded) Program 19.1 (concluded)

// check the spelling spellChecker(fileName);

}

< method spellchecker() listed in the program discussion >

}

(17)

Program 19.1 Program 19.1 (File “spell.txt”) (File “spell.txt”)

teh message contians the url for the web-page and a misspeled url for the email adress

(18)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.1 (Run) Program 19.1 (Run)

Enter the document to spell check: spell.txt teh

'a'(add) 'i'(ignore) 'm'(misspelled) m contians

'a'(add) 'i'(ignore) 'm'(misspelled) m url

'a'(add) 'i'(ignore) 'm'(misspelled) a web-page

'a'(add) 'i'(ignore) 'm'(misspelled) i misspeled

'a'(add) 'i'(ignore) 'm'(misspelled) m email

'a'(add) 'i'(ignore) 'm'(misspelled) i adress

'a'(add) 'i'(ignore) 'm'(misspelled) m

Misspelled words: [adress, contians, misspeled, teh]

(19)

Set Operators

Set Operators

(20)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Design for Implementation of Design for Implementation of

Set Operations Set Operations

public static <T> Set<T> setOp(Set<T> setA, Set<T> setB) {

Set<T> returnSet;

// returnSet is a TreeSet or HashSet object depending on // argument type

if (setA instanceof OrderedSet) returnSet = new TreeSet<T>();

else

returnSet = new HashSet<T>();

. . . }

(21)

union(setA, setB) union(setA, setB)

public static <T> Set<T> union (Set<T> setA, Set<T> setB)

{

Set<T> setUnion;

// allocate concrete collection object for setUnion . . .

// use iterator to add elements from setA Iterator<T> iterA = setA.iterator();

while (iterA.hasNext())

setUnion.add(iterA.next());

// use iterator to add non-duplicate // elements from setB

Iterator<T> iterB = setB.iterator();

while (iterB.hasNext())

setUnion.add(iterB.next());

return setUnion;

}

(22)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

intersection(setA, setB) intersection(setA, setB)

public static <T> Set<T> intersection ( Set<T> setA, Set<T> setB)

{

Set<T> setIntersection;

T item;

// allocate concrete collection object // for setIntersection

. . .

(23)

intersection(setA, setB) intersection(setA, setB)

(concluded) (concluded)

// scan elements in setA and check whether // they are also elements in setB

Iterator<T> iterA = setA.iterator();

while (iterA.hasNext()) {

item = iterA.next();

if (setB.contains(item))

setIntersection.add(item);

}

return setIntersection;

}

(24)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

difference(setA, setB) difference(setA, setB)

public static <T> Set<T> difference ( Set<T> setA, Set<T> setB)

{

Set<T> setDifference;

T item;

// allocate concrete collection object // for setDifference

. . .

(25)

difference(setA, setB) difference(setA, setB)

(concluded) (concluded)

// scan elements in setA and check whether // they are not in setB

Iterator<T> iterA = setA.iterator();

while (iterA.hasNext()) {

item = iterA.next();

if (!setB.contains(item)) setDifference.add(item);

}

return setDifference;

}

(26)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

subset(setA, setB) subset(setA, setB)

public static <T> boolean subset(

Set<T> setA, Set<T> setB) {

return intersection(setA, setB).size() ==

setA.size();

}

(27)

Program 19.2 Program 19.2

import java.io.*;

import java.util.Scanner;

import ds.util.Sets;

import ds.util.TreeSet;

import ds.util.Set;

public class Program19_2 {

public static void main(String[] args) {

// declare sets for current and new // computer accounts

Set<String> oldAcct = new TreeSet<String>(),

currAcct = new TreeSet<String>(), processAcct, newAcct, carryOverAcct, obsoleteAcct;

(28)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.2 (continued) Program 19.2 (continued)

// input names from file into the set try

{

readAccounts("oldAcct.dat", oldAcct);

readAccounts("currAcct.dat", currAcct);

}

catch(IOException ioe) {

System.err.println("Cannot open account file");

System.exit(1);

}

// use set union to determine all // accounts to update

processAcct =

Sets.union(currAcct, oldAcct);

(29)

Program 19.2 (continued) Program 19.2 (continued)

// use set intersection to determine // carryover accounts

carryOverAcct =

Sets.intersection(currAcct, oldAcct);

// use set difference to determine new // and obsolete accounts

newAcct = Sets.difference(currAcct, oldAcct);

obsoleteAcct = Sets.difference(oldAcct, currAcct);

(30)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.2 (continued) Program 19.2 (continued)

// output statements provide a set // description and a list of elements // in the set

System.out.println("Old Accounts: " + oldAcct);

System.out.println("Current Accounts: " + currAcct);

System.out.println("Process Accounts: " + processAcct);

System.out.println("New Accounts: " + newAcct);

System.out.println("Carryover Accounts: " + carryOverAcct);

System.out.println("Obsolete Accounts: " + obsoleteAcct);

}

(31)

Program 19.2 (concluded) Program 19.2 (concluded)

public static void readAccounts(

String filename, Set<String> t) throws IOException {

Scanner sc = new Scanner(

new FileReader(filename));

String acctName;

// input the set of current accounts while(sc.hasNext())

{

acctName = sc.next();

t.add(acctName);

} } }

(32)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.2 (Run) Program 19.2 (Run)

Old Accounts: [fbrue, gharris, lhung, tmiller]

Current Accounts: [ascott, fbrue, wtubbs]

Process Accounts: [ascott, fbrue, gharris, lhung, tmiller, wtubbs]

New Accounts: [ascott, wtubbs]

Carryover Accounts: [fbrue]

Obsolete Accounts: [gharris, lhung, tmiller]

(33)

Ordered Set Operations Ordered Set Operations

 If a set is ordered, set operations can be If a set is ordered, set operations can be performed by using iterators that scan performed by using iterators that scan

each set.

each set.

(34)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Ordered Set Intersection Ordered Set Intersection

Algorithm Algorithm

 The ordered set-intersection algorithm The ordered set-intersection algorithm

uses iterators to make a pairwise scan of uses iterators to make a pairwise scan of

the elements in the two sets. At each the elements in the two sets. At each

step, a comparison is made between step, a comparison is made between

elements and if a match occurs, the value elements and if a match occurs, the value

belongs to the intersection.

belongs to the intersection.

(35)

Ordered Set Intersection Ordered Set Intersection

Algorithm (continued)

Algorithm (continued)

(36)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

advance() advance()

// if more elements remain, return the // next value; otherwise, return null

private static <T> T advance(Iterator<T> iter) {

T value = null;

if (iter.hasNext())

value = iter.next();

return value;

}

(37)

orderedIntersection() orderedIntersection()

public static <T extends Comparable<? super T>>

TreeSet<T> orderedIntersection(TreeSet<T> lhs, TreeSet<T> rhs)

{

// construct intersection

TreeSet<T> setIntersection = new TreeSet<T>();

// iterators that traverse the sets Iterator<T> lhsIter = lhs.iterator(), rhsIter = rhs.iterator();

T lhsValue, rhsValue;

lhsValue = advance(lhsIter);

rhsValue = advance(rhsIter);

(38)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

orderedIntersection() orderedIntersection()

(continued) (continued)

// move forward as long as we have not // reached the end of either set

while (lhsValue != null && rhsValue != null) {

if (lhsValue.compareTo(rhsValue) < 0) // lhsValue < rhsValue; move to // next value in lhs

lhsValue = advance(lhsIter);

else if (rhsValue.compareTo(lhsValue) < 0) // rhsValue < lhsValue; move to

// next value in rhs

rhsValue = advance(rhsIter);

(39)

orderedIntersection() orderedIntersection()

(concluded) (concluded)

else {

// lhsValue == rhsValue; add it // to intersection and move to // next value in both sets

setIntersection.add(lhsValue);

lhsValue = advance(lhsIter);

rhsValue = advance(rhsIter);

} }

return setIntersection;

}

(40)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Complexity of Complexity of

orderdIntersection() orderdIntersection()

 Assume the n Assume the n

lhslhs

and n and n

rhsrhs

are the number of are the number of elements in setA and setB. Each iteration elements in setA and setB. Each iteration

of the loop makes one or two comparisons of the loop makes one or two comparisons

which we assume occur in O(1) running which we assume occur in O(1) running

time. We must make at most n

time. We must make at most n

lhslhs

+ n + n

rhsrhs

comparisons, so the algorithm has worst- comparisons, so the algorithm has worst-

case running time O(n

case running time O(n

lhslhs

+ n + n

rhsrhs

). The ). The

algorithm is linear with respect to the total algorithm is linear with respect to the total

number of elements in the two sets.

number of elements in the two sets.

(41)

Maps Maps

 A map stores data in entries, which are A map stores data in entries, which are

key value pairs. A key serves like an array ‑ key value pairs. A key serves like an array ‑

index to locate the corresponding value in index to locate the corresponding value in

the map. As a result, we call a map an the map. As a result, we call a map an

associative array.

associative array.

(42)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

The Map Interface The Map Interface

The methods size(), isEmpty() and The methods size(), isEmpty() and

clear() are identical to those of the Collection clear() are identical to those of the Collection

interface.

interface.

Methods containsKey() and remove() use only the Methods containsKey() and remove() use only the key as an argument.

key as an argument.

Methods get() and put() access and modify a value Methods get() and put() access and modify a value using the key.

using the key.

A map does not have an iterator to scan its elements. A map does not have an iterator to scan its elements.

Two methods keySet() and entrySet() return the keys and Two methods keySet() and entrySet() return the keys and the entries in a map as a set.

the entries in a map as a set.

(43)

The Map Interface (concluded)

The Map Interface (concluded)

(44)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

TreeMap Class TreeMap Class

 TreeMap is an ordered collection that TreeMap is an ordered collection that

accesses elements in the ascending order accesses elements in the ascending order

of its keys. The class implements the of its keys. The class implements the

OrderedMap interface that includes the OrderedMap interface that includes the

methods firstKey() and lastKey() which methods firstKey() and lastKey() which

return the value corresponding to the return the value corresponding to the

minimum and maximum key respectively.

minimum and maximum key respectively.

(45)

TreeMap Class (continued)

TreeMap Class (continued)

(46)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

TreeMap Class (concluded) TreeMap Class (concluded)

// arrays for three classes and their enrollment

String[] className = {"ECON 101","CS 173","ENGL 25"};

int[] enrollment = {85,14, 30};

// create a TreeMap object

TreeMap<String, Integer> tm = new TreeMap<String, Integer>();

// the key argument is a string from className and the value // argument is the corresponding Integer object from enrollment for(int i = 0; i < 3; i++)

tm.put(className[i], enrollment[i]);

(47)

Program 19.3 Program 19.3

import java.util.Scanner;

import java.io.FileReader;

import java.io.FileNotFoundException;

import ds.util.TreeMap;

import ds.time.Time24;

public class Program19_3 {

public static void main(String[] args) {

// a TreeMap object whose entries are a student // name and the total hours worked during a

// week; use a Time24 object for the value // component of an entry

TreeMap<String, Time24> timecardMap = new TreeMap<String,Time24>();

Time24 workTime, timeValue;

(48)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.3 (continued) Program 19.3 (continued)

// object used to input the data from // file "studwk.dat"

Scanner fin = null;

try {

fin = new Scanner(new FileReader("studwk.dat"));

}

catch (FileNotFoundException fnfe) {

System.err.println("Cannot open " + "\"studwk.dat\"");

System.exit(1);

}

// variables to store input data String studName, endStuff;

int workhour, workminute;

(49)

Program 19.3 (continued) Program 19.3 (continued)

// input successive lines in the file consisting // of the student name and the scheduled work time while (fin.hasNext())

{

studName = fin.next();

// get hours and minutes from the input line workhour = fin.nextInt();

workminute = fin.nextInt();

workTime = new Time24(workhour, workminute);

// access the entry corresponding to // the student name

timeValue = timecardMap.get(studName);

(50)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.3 (concluded) Program 19.3 (concluded)

// if timeValue is null, we have a new entry // with a Time24 object as the value

if (timeValue == null)

timecardMap.put(studName, new Time24(

workhour, workminute));

else

// update the current Time24 value and // put entry back into the timecardMap {

timeValue.addTime(workhour*60 + workminute);

timecardMap.put(studName, timeValue);

} }

// display the timecardMap

System.out.println("Student-Time: " + timecardMap);

} }

(51)

Program 19.3 Program 19.3 (File and Run) (File and Run)

File: "studwk.dat"

Tolan 4 15 Dong 3 00 Tolan 3 15 Weber 5 30 Tolan 2 45 Brock 4 20 Dong 4 00 Dong 3 30 Tolan 3 15 Weber 2 30 Run:

Student-Time: {Brock=4:20, Dong=10:30, Tolan=13:30, Weber=8:00}

(52)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.4 Program 19.4

import java.io.FileReader;

import java.io.FileNotFoundException;

import java.util.Scanner;

import ds.util.TreeMap;

import ds.util.TreeSet;

public class Program19_4 {

public static void main(String[] args) {

// softwareMap holds entries that are // (String, TreeSet<String>) pairs

TreeMap<String, TreeSet<String>> softwareMap = new TreeMap<String, TreeSet<String>>();

Scanner fin = null;

TreeSet<String> prodSet;

String company, product;

(53)

Program 19.4 (continued) Program 19.4 (continued)

try {

fin = new Scanner(new FileReader(

"product.dat"));

fin.useDelimiter("[\t\n\r]+");

}

catch (FileNotFoundException fnfe) {

System.err.println("Cannot open " + "\"product.dat\"");

System.exit(1);

}

while(fin.hasNext()) {

// get company and product names company = fin.next();

product = fin.next();

(54)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.4 (concluded) Program 19.4 (concluded)

// return value (set) corresponding // to company name

prodSet = softwareMap.get(company);

// if no entry exists, create an empty set if (prodSet == null)

prodSet = new TreeSet<String>();

// add product name to the set; then // add entry with company as key

// and prodSet as value prodSet.add(product);

softwareMap.put(company, prodSet);

}

// display contents of the softwareMap System.out.println(softwareMap);

} }

(55)

Program 19.4 Program 19.4 (File and Run) (File and Run)

File <product.dat> with tab-separated data Microsoft Visual C++

Borland C++ Builder Microsoft Word

Ramsoft EZJava Borland J Builder Adobe Photoshop Microsoft Excel

Adobe Illustrator Run:

{Adobe=[Illustrator, Photoshop], Borland=[C++ Builder, J Builder], Microsoft=[Excel, Visual C++, Word],

Ramsoft=[EZJava]}

(56)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Map Collection View Map Collection View

 A map does not have an iterator for A map does not have an iterator for

accessing its elements. This task is left to accessing its elements. This task is left to

other objects, called collection views, other objects, called collection views,

which are sets that support the methods which are sets that support the methods

in the Set interface but act on the original in the Set interface but act on the original

map as the

map as the backing collection backing collection . .

(57)

Map Collection View Map Collection View

(continued) (continued)

In the Map interface, the method keySet() In the Map interface, the method keySet() returns a set of keys in the map. This

returns a set of keys in the map. This

collection view implements the Set interface.

collection view implements the Set interface.

Set<String> keys = airports.keySet();

Set<String> keys = airports.keySet();

(58)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

The Key Set Collection View The Key Set Collection View

 A keySet() view is a set of keys in the A keySet() view is a set of keys in the

map. Deleting a key from the set removes map. Deleting a key from the set removes

the corresponding entry from the map.

the corresponding entry from the map.

(59)

The Key Set Collection View The Key Set Collection View

(concluded) (concluded)

 The Set interface defines an add() The Set interface defines an add() operation and so a map class must operation and so a map class must

implement the method for its key view.

implement the method for its key view.

The operation does not make sense. A The operation does not make sense. A

key-value pair must be inserted in the key-value pair must be inserted in the

backing collection. Map classes include backing collection. Map classes include

code that throws an code that throws an

UnsupportedOperationException

UnsupportedOperationException . .

(60)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

The Entry Set Collection View The Entry Set Collection View

 In the Map interface, a second view, In the Map interface, a second view, called an

called an entry set entry set , is the set of key-value , is the set of key-value entries which is returned by the map

entries which is returned by the map method entrySet().

method entrySet().

Elements of a map implement the Entry Elements of a map implement the Entry interface, which is defined as an interface interface, which is defined as an interface

inside the Map interface. Entry set objects inside the Map interface. Entry set objects

implement the Map.Entry interface also.

implement the Map.Entry interface also.

Set<Map.Entry<String, Integer>> entries = tm.entrySet();

(61)

The Entry Set Collection View The Entry Set Collection View

(continued)

(continued)

(62)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

The Entry Set Collection View The Entry Set Collection View

(continued) (continued)

 The map entrySet view is a set of The map entrySet view is a set of

Map.Entry objects from the backing map.

Map.Entry objects from the backing map.

Operations on the set affect the map.

Operations on the set affect the map.

The set can be used to define iterators that The set can be used to define iterators that scan the elements in the map. Entry set

scan the elements in the map. Entry set iterators provide us the equivalent of map iterators provide us the equivalent of map iterators with the ability to access an entry's iterators with the ability to access an entry's key component and both access and update key component and both access and update an entry's value component. In particular, the an entry's value component. In particular, the iterator method remove() removes an entry iterator method remove() removes an entry from the map.

from the map.

(63)

Entry Set Iterators Entry Set Iterators

You can use the Set methods size(), You can use the Set methods size(),

isEmpty(), clear() and so forth with an entry isEmpty(), clear() and so forth with an entry set. However, you will typically use an entry set. However, you will typically use an entry

set iterator. Such an iterator provides the set iterator. Such an iterator provides the

only way to scan the entries in the map. At only way to scan the entries in the map. At

any point in the iteration, the iterator any point in the iteration, the iterator

references a Map.Entry element in the map references a Map.Entry element in the map and the programmer can use the Map.Entry and the programmer can use the Map.Entry

interface methods to access the components.

interface methods to access the components.

(64)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Entry Set Iterators (continued) Entry Set Iterators (continued)

 The map, confTimeMap, represents The map, confTimeMap, represents

conference activities and their scheduled conference activities and their scheduled

times.

times.

// create map and add entries

TreeMap<String, Time24> confTimeMap =

new TreeMap<String, Time24>();

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));

(65)

Entry Set Iterators (continued) Entry Set Iterators (continued)

// declare an entry set for map confTimeMap

Set<Map.Entry<String,Time24>> entries = confTimeMap.entrySet();

// declare an iterator for the entry set using the Set iterator() // method

Iterator<Map.Entry<String, Time24>> iter = entries.iterator();

(66)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Entry Set Iterators (continued) Entry Set Iterators (continued)

 Assume the conference is delayed so Assume the conference is delayed so that all of the day's activities must be that all of the day's activities must be

pushed forward one-half hour. After using pushed forward one-half hour. After using

the iterator method next() to extract an the iterator method next() to extract an

entry, addTime() increases the Time24 entry, addTime() increases the Time24

value component by 30 minutes.

value component by 30 minutes.

// use a loop to scan the entries in the map while (iter.hasNext())

{

// extract the next element as a Map.Entry object Map.Entry<String, Time24> me = iter.next();

// the value component (me.getValue()) is a Time24 object;

// add 30 minutes and assign the new value to the entry Time24 t = me.getValue();

t.addTime(30);

me.setValue(t);

}

(67)

Entry Set Iterators (continued) Entry Set Iterators (continued)

 If we want to list only the sessions and If we want to list only the sessions and their starting time, we can use the same their starting time, we can use the same

iteration pattern. Visit each element as a iteration pattern. Visit each element as a

Map.Entry object and then use getKey() to Map.Entry object and then use getKey() to

access the key component which has access the key component which has

String type.

String type.

(68)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Entry Set Iterators (concluded) Entry Set Iterators (concluded)

// use a foreach loop to scan the entries in the map

// and output the starting time of each conference session for (Map.Entry<String,Time24> i : entries)

{

// the key component (me.getKey()) is a String object;

// check if it contains the substring "Session"; if so, // output name and time

String activity = (String)i.getKey();

if (activity.indexOf("Session") != -1)

System.out.println("Activity " + activity +

" Starting time " + i.getValue());

}

Output:

Activity Session 1 Starting time 10:00 Activity Session 2 Starting time 14:30

(69)

Program 19.5 Program 19.5

 A A concordance concordance is a software tool that is a software tool that reads a text file and extracts all of the reads a text file and extracts all of the

words along with the line numbers on words along with the line numbers on

which the words appear. Compilers often which the words appear. Compilers often

provide a concordance to evaluate the use provide a concordance to evaluate the use

of identifiers (including keywords) in a of identifiers (including keywords) in a

source code file. This application designs source code file. This application designs

and implements such a concordance using and implements such a concordance using

a map.

a map.

(70)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.5 (continued) Program 19.5 (continued)

import java.io.*;

import java.util.regex.*;

import java.util.StringTokenizer;

import java.util.Scanner;

import ds.util.*;

public class Program19_5 {

private static Pattern identifierPattern = Pattern.compile("[a-zA-Z][a-zA-Z0-9]*");

public static void main(String[] args) throws IOException

{

String filename;

Scanner keyIn = new Scanner(System.in);

// get the file name

System.out.print("Enter the file name: ");

filename = keyIn.nextLine();

System.out.println();

(71)

Program 19.5 (continued) Program 19.5 (continued)

// create the concordance concordance(filename);

}

// builds concordance and calls // writeConcordance() for output

public static void concordance(String filename) throws IOException

{

// concordance map and set for line numbers

TreeMap<String, TreeSet<Integer>> concordanceMap = new TreeMap<String, TreeSet<Integer>>();

TreeSet<Integer> lineNumbers;

String inputLine, identifier;

int lineNumber = 0;

// create scanner to input from document file

Scanner fin = new Scanner(new FileReader(filename));

Matcher matcher = null;

(72)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.5 (continued) Program 19.5 (continued)

// read the file a line at a time while(fin.hasNext())

{

// get next line

inputLine = fin.nextLine();

lineNumber++;

// create matcher to find identifiers // in inputLine

matcher = identifierPattern.matcher(inputLine);

// extract identifiers until end of line while (matcher.find())

{

identifier = inputLine.substring(

matcher.start(), matcher.end());

(73)

Program 19.5 (continued) Program 19.5 (continued)

// get value (TreeSet) from entry with // identifier as key; if it does not // exist (null), create TreeSet object

lineNumbers = concordanceMap.get(identifier);

if ( lineNumbers == null )

lineNumbers = new TreeSet<Integer>();

// add a new line number to set of // line numbers

lineNumbers.add(lineNumber);

concordanceMap.put(identifier, lineNumbers);

} }

// output the concordance

writeConcordance(concordanceMap);

}

(74)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.5 (continued) Program 19.5 (continued)

public static void writeConcordance(

TreeMap<String,TreeSet<Integer>> map) {

Set<Map.Entry<String,TreeSet<Integer>>> entries = map.entrySet();

TreeSet<Integer> lineNumberSet;

Iterator<Map.Entry<String,TreeSet<Integer>>> iter = entries.iterator();

Iterator<Integer> setIter;

int i;

while (iter.hasNext()) {

Map.Entry<String,TreeSet<Integer>> e = iter.next();

System.out.print(e.getKey()); // output key // pad output to 12 characters using blanks if (e.getKey().length() < 12)

for (i=0;i < 12 - (e.getKey().length()); i++) System.out.print(' ');

(75)

Program 19.5 (continued) Program 19.5 (continued)

// extract the value component as a TreeSet lineNumberSet = e.getValue();

// display number of lines containing // the identifier and the actual lines System.out.print(

formatInt(4, lineNumberSet.size()) + ": ");

setIter = lineNumberSet.iterator();

while (setIter.hasNext())

System.out.print(setIter.next() + " ");

System.out.println();

}

System.out.println();

}

(76)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.5 (concluded) Program 19.5 (concluded)

// private method formatInt() with integer arguments // w and n; returns a formatted string with integer n // right-justified in a field of w spaces; used to // line up output in concordance

private static String formatInt(int w, int n) { . . . }

}

(77)

Program 19.5 Program 19.5

(File "concord.txt“) (File "concord.txt“)

int m = 12, n = 14;

double a = 3, b = 2, hypotenuse if (n <= 5)

n = 2*m;

else

n = m * m;

hypotenuse = sqrt(a*a + b*b);

(78)

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Program 19.5 (Run) Program 19.5 (Run)

Enter the file name: concord.txt a 2: 2 8

b 2: 2 8 double 1: 2

else 1: 6

hypotenuse 2: 2 8 if 1: 4

int 1: 1

m 3: 1 5 7

n 4: 1 4 5 7 sqrt 1: 8

Referensi

Garis besar

Dokumen terkait

opentripplanner-routing/src/main/java/org/opentripplanner/routing/core/RoutingRequest.java package org.opentripplanner.routing.core; import java.io.Serializable; import