Transcript Slide 1

Data Structures for Java
William H. Ford
William R. Topp
Chapter 19
Sets and Maps
Bret Ford
© 2005, Prentice Hall
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Set Collection

A Set implements the Collection interface
and requires that each element be unique.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Map

A map stores an element as a key-value
pair. In a pair, the first field is the key
which is an attribute that uniquely
identifies the element. The second field is
the value which is an object associated
with the key.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Map (continued)

The figure illustrates a map that might
be used for university administration.
The map is a collection of String-Integer
pairs to denote the number of majors in
each of its degree programs. The name of
the degree program is the key and the
number of majors is the value
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Map (continued)

A map collection uses the key to access
the value field of the entry. For instance,
assume degreeMap is the map collection
for departments and major counts. The
operation degreeMap.get("English")
returns the Integer component with value
117, which identifies the number of
English majors.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Map (concluded)

The Set interface extends the Collection
interface, but the Map interface is
separate, since if defines methods not
relevant to general collections.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Set and Map Interfaces

The interfaces and collection classes
that define sets and maps. The dashed
lines indicate that the class implements
the interface.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
TreeSet Collection

TreeSet is implemented by a binary search
tree. As a result, it implements the
OrderedSet interface that extends the Set
interface and defines the methods first()
and last().
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
TreeSet Collection
(concluded)
class TreeSet<T> implements OrderedSet<T>
ds.util
Constructor
TreeSet()
Creates an empty ordered set whose elements have a specified type that
must implement the Comparable interface
Methods
T first()
Returns the minimum value of the elements in the set
T last()
Returns the maximum value of the elements in the set
String toString()
Returns a string containing a comma separated ordered list of elements
enclosed in brackets.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Spell Checker

A set is an ideal structure for the
implementation of a simple spelling
checker.


The file "dict.dat" is a set of strings containing
approximately 25,000 words in lower case.
Open the file using the Scanner class.
For each word, call contains() to determine
whether the word is in the dictionary set. If
not, assume the word is misspelled and
interact with the user for instructions on how
to proceed.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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));
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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);
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
spellChecker() (continued)
// read the document word by word and check spelling
while(docFile.hasNext())
{
// get the next word from the document
word = docFile.next();
//
//
//
//
if
{
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
(!dictionary.contains(word))
System.out.println(word);
System.out.print(
"
'a'(add) 'i'(ignore)
"'m'(misspelled) ");
response = keyIn.next();
" +
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
spellChecker() (concluded)
//
//
//
if
if response is 'a' add to dictionary;
if not ignored, add to set of
misspelled words
(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);
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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();
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Program 19.1 (concluded)
// check the spelling
spellChecker(fileName);
}
< method spellchecker() listed in the
program discussion >
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Program 19.1
(File “spell.txt”)
teh message contians the url for the web-page
and a misspeled url for the email adress
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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]
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Set Operators
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Design for Implementation of
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>();
. . .
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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;
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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
. . .
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
intersection(setA, setB)
(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;
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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
. . .
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
difference(setA, setB)
(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;
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
subset(setA, setB)
public static <T> boolean subset(
Set<T> setA, Set<T> setB)
{
return intersection(setA, setB).size() ==
setA.size();
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Program 19.2
import
import
import
import
import
java.io.*;
java.util.Scanner;
ds.util.Sets;
ds.util.TreeSet;
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;
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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);
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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);
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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);
" +
" +
" +
" +
" +
" +
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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);
}
}
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Program 19.2 (Run)
Old Accounts:
Current Accounts:
Process Accounts:
[fbrue, gharris, lhung, tmiller]
[ascott, fbrue, wtubbs]
[ascott, fbrue, gharris, lhung,
tmiller, wtubbs]
New Accounts:
[ascott, wtubbs]
Carryover Accounts: [fbrue]
Obsolete Accounts: [gharris, lhung, tmiller]
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Ordered Set Operations

If a set is ordered, set operations can be
performed by using iterators that scan
each set.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Ordered Set Intersection
Algorithm

The ordered set-intersection algorithm
uses iterators to make a pairwise scan of
the elements in the two sets. At each
step, a comparison is made between
elements and if a match occurs, the value
belongs to the intersection.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Ordered Set Intersection
Algorithm (continued)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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;
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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);
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
orderedIntersection()
(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);
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
orderedIntersection()
(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;
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Complexity of
orderdIntersection()

Assume the nlhs and nrhs are the number of
elements in setA and setB. Each iteration
of the loop makes one or two comparisons
which we assume occur in O(1) running
time. We must make at most nlhs + nrhs
comparisons, so the algorithm has worstcase running time O(nlhs + nrhs). The
algorithm is linear with respect to the total
number of elements in the two sets.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Maps

A map stores data in entries, which are
key-value pairs. A key serves like an array
index to locate the corresponding value in
the map. As a result, we call a map an
associative array.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
The Map Interface




The methods size(), isEmpty() and
clear() are identical to those of the
Collection interface.
Methods containsKey() and remove() use
only the key as an argument.
Methods get() and put() access and
modify a value using the key.
A map does not have an iterator to scan
its elements.

Two methods keySet() and entrySet() return
the keys and the entries in a map as a set.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
The Map Interface (concluded)
interface MAP<K,V> (partial)
ds.util
void clear()
Removes all mappings from this map.
boole containsKey(Object key)
an
Returns true if this map contains a mapping for the specified key.
boole isEmpty()
an
Returns true if this map contains no key-value mappings.
V remove(Object key)
Removes the mapping for this key from this map if present. Returns the previous
value associated with specified key, or null if there was no mapping for key.
int size()
Returns the number of key-value mappings in this map.
Access/Update Methods
K get(Object key)
Returns the value to which this map maps the specified key or null if the map
contains no mapping for this key.
V put(K key, V value)
Associates the specified value with the specified key in this map. Returns the
previous value associated with key, or null if there was no mapping for key.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
TreeMap Class

TreeMap is an ordered collection that
accesses elements in the ascending order
of its keys. The class implements the
OrderedMap interface that includes the
methods firstKey() and lastKey() which
return the value corresponding to the
minimum and maximum key respectively.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
TreeMap Class (continued)
class TreeMap<K,V> implements OrderedMap<K,V>
ds.util
Constructor
TreeMap()
Creates an empty ordered map. The key type K must implement
Comparable.
Methods
T firstKey()
Returns the value associated with the entry that has the minimum key.
T lastKey()
Returns the value associated with the entry that has the maximum key.
String toString()
Returns a comma-separated list of entries enclosed in braces ("{}"). Each
entry has the format "key = value".
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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]);
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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;
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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;
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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);
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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);
}
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Program 19.3
(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}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Program 19.4
import
import
import
import
import
java.io.FileReader;
java.io.FileNotFoundException;
java.util.Scanner;
ds.util.TreeMap;
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;
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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();
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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);
}
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Program 19.4
(File and Run)
File <product.dat> with tab-separated data
Microsoft
Borland
Microsoft
Ramsoft
Borland
Adobe
Microsoft
Adobe
Visual C++
C++ Builder
Word
EZJava
J Builder
Photoshop
Excel
Illustrator
Run:
{Adobe=[Illustrator, Photoshop], Borland=[C++ Builder,
J Builder], Microsoft=[Excel, Visual C++, Word],
Ramsoft=[EZJava]}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Map Collection View

A map does not have an iterator for
accessing its elements. This task is left to
other objects, called collection views,
which are sets that support the methods
in the Set interface but act on the original
map as the backing collection.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Map Collection View
(continued)

In the Map interface, the method keySet()
returns a set of keys in the map. This
collection view implements the Set
interface.
Set<String> keys = airports.keySet();
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
The Key Set Collection View

A keySet() view is a set of keys in the
map. Deleting a key from the set removes
the corresponding entry from the map.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
The Key Set Collection View
(concluded)

The Set interface defines an add()
operation and so a map class must
implement the method for its key view.
The operation does not make sense. A
key-value pair must be inserted in the
backing collection. Map classes include
code that throws an
UnsupportedOperationException.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
The Entry Set Collection View

In the Map interface, a second view, called
an entry set, is the set of key-value entries
which is returned by the map method
entrySet().

Elements of a map implement the Entry
interface, which is defined as an interface
inside the Map interface. Entry set objects
implement the Map.Entry interface also.
Set<Map.Entry<String, Integer>> entries = tm.entrySet();
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
The Entry Set Collection View
(continued)
interface MAP.ENTRY<K,V>
ds.util.Map
K getKey()
Returns the key corresponding to this entry..
V getValue()
Returns the value corresponding to this entry..
V setValue(V value)
Replaces the value corresponding to this entry with the specified value. Returns
the old value corresponding to the entry
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
The Entry Set Collection View
(continued)

The map entrySet view is a set of
Map.Entry objects from the backing map.
Operations on the set affect the map.

The set can be used to define iterators that
scan the elements in the map. Entry set
iterators provide us the equivalent of map
iterators with the ability to access an entry's
key component and both access and update
an entry's value component. In particular, the
iterator method remove() removes an entry
from the map.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Entry Set Iterators

You can use the Set methods size(),
isEmpty(), clear() and so forth with an
entry set. However, you will typically use
an entry set iterator. Such an iterator
provides the only way to scan the entries
in the map. At any point in the iteration,
the iterator references a Map.Entry
element in the map and the programmer
can use the Map.Entry interface methods
to access the components.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Entry Set Iterators (continued)

The map, confTimeMap, represents
conference activities and their scheduled
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));
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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();
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Entry Set Iterators (continued)

Assume the conference is delayed so
that all of the day's activities must be
pushed forward one-half hour. After using
the iterator method next() to extract an
entry, addTime() increases the Time24
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);
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Entry Set Iterators (continued)

If we want to list only the sessions and
their starting time, we can use the same
iteration pattern. Visit each element as a
Map.Entry object and then use getKey() to
access the key component which has
String type.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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
Activity
Session 1
Session 2
Starting time 10:00
Starting time 14:30
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Program 19.5

A concordance is a software tool that
reads a text file and extracts all of the
words along with the line numbers on
which the words appear. Compilers often
provide a concordance to evaluate the use
of identifiers (including keywords) in a
source code file. This application designs
and implements such a concordance using
a map.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Program 19.5 (continued)
import
import
import
import
import
java.io.*;
java.util.regex.*;
java.util.StringTokenizer;
java.util.Scanner;
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();
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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;
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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());
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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);
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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(' ');
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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();
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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)
{ . . . }
}
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Program 19.5
(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);
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Program 19.5 (Run)
Enter the file name: concord.txt
a
b
double
else
hypotenuse
if
int
m
n
sqrt
2:
2:
1:
1:
2:
1:
1:
3:
4:
1:
2
2
2
6
2
4
1
1
1
8
8
8
8
5
4
7
5
7
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.