+ All Categories
Home > Documents > mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to...

mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to...

Date post: 23-Nov-2020
Category:
Upload: others
View: 2 times
Download: 0 times
Share this document with a friend
18
CS 1302 – Chapter 21 Maps These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues from Ch 13 and will be very similar to what you do on the next homework. There also is an example in section 21.13 that is an excellent short example of using a map. 21.8 – Maps 1. Frequently, it is convenient to associate a unique key with each of the items that we want to store in a collection and later be able to retrieve the item by supplying the key. In computing we call these key-value pairs. For example: Dictionary: each word (key) is associated with a definition (value) Phone book: each name (key) is associated with a phone number (value). Banner: a student number (key) is associated with each student’s records (value). 2. A Map is a type of collection that stores key-value pairs. The example on the left below shows a map entry that consists of a key which is a person’s SSN and a value which is the corresponding person’s name. The figure on the right below shows a map with a number of map entries. 3. In a Map, the keys are a Set (so no duplicate keys are allowed) and the values are a Collection (so duplicates could exist. In other words, different keys could map to the same value). 4. In Java, the Map interface is parallel to the Collection interface (i.e. not a sub-interface) as shown in the diagrams below. Java provides three common implementations: 1
Transcript
Page 1: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

CS 1302 – Chapter 21Maps

These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues from Ch 13 and will be very similar to what you do on the next homework. There also is an example in section 21.13 that is an excellent short example of using a map.

21.8 – Maps

1. Frequently, it is convenient to associate a unique key with each of the items that we want to store in a collection and later be able to retrieve the item by supplying the key. In computing we call these key-value pairs. For example:

Dictionary: each word (key) is associated with a definition (value) Phone book: each name (key) is associated with a phone number (value). Banner: a student number (key) is associated with each student’s records (value).

2. A Map is a type of collection that stores key-value pairs. The example on the left below shows a map entry that consists of a key which is a person’s SSN and a value which is the corresponding person’s name. The figure on the right below shows a map with a number of map entries.

3. In a Map, the keys are a Set (so no duplicate keys are allowed) and the values are a Collection (so duplicates could exist. In other words, different keys could map to the same value).

4. In Java, the Map interface is parallel to the Collection interface (i.e. not a sub-interface) as shown in the diagrams below. Java provides three common implementations:

a. HashMap – The map entries have no particular order.b. LinkedHashMap – The map entries are ordered according to the order they were inserted. c. TreeMap – The map entries are ordered according to their keys where Comparable or Comparator is used

for the ordering.

1

Page 2: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

21.9 – The HashMap Class

1. The Java API defines the Map interface. A Map is a type of “collection”, but it is not a Collection. The Map interface is shown on the right and is a root interface. HashMap is a concrete implementation of Map.

2. To create a HashMap we must specify the generic types for the key and the value. For example, consider a situation where we define a map where the key is a person’s name (String) and the value is the score (Integer) the person earned in a game. Thus, we define the map this way:

Map<String,Integer> hmScores = new HashMap<>();

a. The put(key,value) method is used to add a map entry to a map. For example:

hmScores.put("Felix", 42);hmScores.put("Bill", 28);

b. The get method is used to retrieve a value given a key. For example:

int score = hmScores.get("Bill");

c. Internally, a map stores its keys in a Set, thus they key in a map must be unique. The keySet method returns the Set of all the keys in a map. For example:

Set<String> names = hmScores.keySet();

returns the Set of all the names in the map. Technically, since a Set is a Collection, you could call all Collection methods on the set. However, some operations, such as add are not supported and will throw an exception. Of course, you could turn the set into a list and then modify the list (which, of course, does not modify the map):

ArrayList<String> namesAL = new ArrayList<>(names);namesAL.add("Lydia");

d. Similar to a HashSet, a HashMap stores its entries in no particular order.

e. Internally, a Map stores its values in a Collection, thus there can be duplicate values in a map as long as they have different keys. For example two people could have the same score:

hmScores.put("Felix", 42);hmScores.put("Dee", 42);

f. The values method returns a Collection of all the values in a map. For example:

Collection<Integer> scores = hmScores.values();

returns the Collection of all the scores in the map. Thus, we can call any Collection methods on scores.

g. One way to iterate over all the key-value pairs is to use a for-each loop over the keys and then use each key to get the corresponding value:

2

Page 3: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

for(String key : hmScores.keySet()) {System.out.println("key=" + key + ", value=" + hmScores.get(key));

}

h. Below are a few other methods from the Map interface:

Method Descriptionclear Removes all map entriescontainsKey(key) Returns true if key is found in the map; otherwise false.containsValue(value) Returns true if value is found in the map; otherwise false.remove(key) Removes the map entry that corresponds to keysize() Returns the number of map entries in the map

3. Example – A common situation is to store instances of a custom class in a map specifying the key as one of the properties of the class. In the example below the value is an Employee object and the key is the employee’s SSN.

// Create mapMap<Integer,Employee> hmEmployees = new HashMap< >();

// Create employeesEmployee e1 = new Employee("Lyton", "Xavier", 243558673, 77.88);...

// Put employee in maphmEmployees.put(e1.getSSNum(), e1);...

// Get all the SSN’sSet<Integer> keys = hmEmployees.keySet();

// Iterate over all the employees via the SSN’sfor(int key : keys) {

Employee e = hmEmployees.get(key);}

// Get all the employeesCollection<Employee> emps = hmEmployees.values();

4. What happens if we try to add a map entry with a duplicate key? It replaces the value at the existing key.

5. How do we iterate over the entries in a HashMap?

a. Get all the keys with the keyset method and iterate over them.b. Get all the values with the values method and iterate over them.c. Get all the keys with the keyset, iterate over them, using each key to access the corresponding value with

the get method.d. (Optional) Get all the entries via the entrySet method. This method returns a Set of Map.Entry objects. A

Map.Entry object contains a key and associated value and contains a getKey and getValue method.

6. As we saw in Lab 11, we can create a map of lists where the values are lists.

7. We can use custom objects as keys in a HashMap; however, it is subject to the same issues as storing custom objects in a HashSet, namely, you must override hashCode and equals.

3

Page 4: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

Practice Problems

1. Suppose you have a LoginAccount class with the following fields (and associated getters): userId, password, name, balance. Given that you have a LinkedList of LoginAccounts named llAccounts write a snippet of code to create a HashMap named hmAccounts of the accounts using the userID (string) as the key.

2. Suppose you have a LinkedList of userID’s (string) named ids and a corresponding LinkedList of passwords (string) named passwords. In other words, the first userID in ids corresponds to the first password in passwords, etc. Write a snippet of code to create a HashMap named hmPasswords of the passwords where the key is the corresponding userID. However, only add the entry if the password has a length at least 6 and at least one number. Also print the number of passwords that did not meet the criteria.

Suppose you have a HashMap, mapScores where the key is the teamID (integer) and the value is the team’s score (double). Write a snippet of code to return a list of the teamID’s that are greater than 5.

3. Suppose you have a HashMap, mapScores where the key is the teamID (integer) and the value is the team’s score (double). Write a snippet of code to add 10.0 to each teams score for the teams with a teamID of 5 or more.

Suppose you have a HashMap, mapAccounts where the key is the accountNum (integer) and the value is an Account object. Account has an accountNum and a balance. Balance has a getBalance and a deposit(amt). Write a snippet of code to deposit 10.0 into each account.

4. Suppose you have two HashMaps, mapScores1 and mapScores2. Each map has a key which is the teamID (integer) and the value which is the team’s score (double). Write a snippet of code to add any entries from mapScores1 that are not in mapScores2 to mapScores2. If a team in mapScores1 is in mapScores2 then modify the value in mapScores2 so that it is the sum of the two scores. For example:

Initially:mapScores1 = {1=100.0, 2=500.0, 3=400.0, 4=200.0, 5=900.0}mapScores2 = {3=200.0, 4=700.0, 8=100.0, 10=400.0}

After code:mapScores2 = {1=100.0, 2=500.0, 3=600.0, 4=900.0, 5=900.0, 8=100.0, 10=400.0}

4

Page 5: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

21.10 – Example

1. Consider the example shown in the class diagram below. We considered this example extensively in Ch 13. A Person has many Animals and also has many Flyers.

2. Previously the two 1-many relationships were implemented as ArrayList:

private ArrayList<Animal> pets = new ArrayList<>();private ArrayList<Flyer> flyers = new ArrayList<>();

Here, we replace the ArrayLists with HashMaps and modify all methods to support this.

private HashMap<String,Animal> pets = new HashMap<>();private HashMap<String,Flyer> flyers = new HashMap<>();

using the Animal’s name as the key and the value is the corresponding Animal object.

The complete code for this example is on the Schedule.

5

Page 6: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

3. The addPet method:

HashMap Implementation ArrayList Implementation (Ch 13)public boolean addPet(Animal a) {

String name = a.getName();if(!pets.containsKey(name)) {

pets.put(name,a);if(a instanceof Flyer) {

Flyer f = (Flyer)a;flyers.put(name,f);

}return true;

}return false;

}

public boolean addPet(Animal a) {if(!pets.contains(a)) {

pets.add(a);if(a instanceof Flyer) {

Flyer f = (Flyer)a;flyers.add(f);

}return true;

}return false;

}

4. We have changed the signature of getPet method so that it accepts the name of a pet whereas with the ArrayList we had to use an index. The removePet method is similar. You should review that in the code yourself .

HashMap Implementation ArrayList Implementation (Ch 13)public Animal getPet(String name) {

if(pets.containsKey(name)) {return pets.get(name);

}return null;

}

public Animal getPet(int i) {if(i>=0 && i<pets.size()) {

return pets.get(i);}return null;

}

5. The getSortedPets method:

HashMap Implementation ArrayList Implementation (Ch 13)public ArrayList<Animal> getSortedPets() {

ArrayList<Animal> sorted = new ArrayList<>(pets.values());

Collections.sort(sorted);return sorted;

}

public ArrayList<Animal> getSortedPets() {

ArrayList<Animal> sorted = new ArrayList<>(pets);

Collections.sort(sorted);return sorted;

}

6. We add a getSortedPetNames method that returns a list of the pet names, sorted.

public ArrayList<String> getSortedPetNames() {ArrayList<String> sorted = new ArrayList<>(pets.keySet());Collections.sort(sorted);return sorted;

}

6

Page 7: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

7. The birdsFlyAndSoar and getDogs methods:

HashMap Implementation ArrayList Implementation (Ch 13)public void birdsFlyAndSoar() {

for(Flyer f : flyers.values()) {f.fly();f.soar();

}}

public ArrayList<Dog> getDogs() {ArrayList<Dog> dogs =

new ArrayList<>();for(Animal a : pets.values()) {

if(a instanceof Dog) {dogs.add((Dog)a);

}}return dogs;

}

public void birdsFlyAndSoar() {for(Flyer f : flyers) {

f.fly();f.soar();

}}

public ArrayList<Dog> getDogs() {ArrayList<Dog> dogs =

new ArrayList<>();for(Animal a : pets) {

if(a instanceof Dog) {dogs.add((Dog)a);

}}return dogs;

}

8. There are several other methods that you should look at yourself in the code: getNumPets (doesn’t change), getPets, makeSound, removePet, removePets, and toString.

21.11 – The LinkedHashMap Class

[Optional – We will not cover this, Fall 2020]

1. The LinkedHashMap class is identical to HashMap except that the order of insertion is preserved.

2. (Optional) – The entries in a LinkedHashMap can also be accessed in the order in which they were last accessed, from least recently accessed to most recently. This is called access order and is specified, for example, by using true for the last argument in the constructor below:

LinkedHashMap(initialCapacity, loadFactor, true).

This can be used in what is called a Least Recently Used Cache (LRU) where you want to maintain a finite sized cache and when a new entry is added which increases the size beyond the desired maximum, the stalest (least recently used) entry is removed. It supports a protected method, removeEldestEntry which can be overridden when extending LinkedHashMap.

7

Page 8: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

Section 21.12 – The TreeMap Class

1. A TreeMap is a map where the keys are ordered.

2. (Optional) As shown in the class diagram above on the right, a TreeMap inherits methods from SortedMap that are analogous to the methods TreeSet inherits from SortedSet:

TreeMap (SortedMap) TreeSet (SortedSet)firstKey():K first():ElastKey():K last():EheadMap(toKey:K) :SortedMap<K,V>

headSet(toElement:E) :SortedSet<E>

tailMap(fromKey:K) :SortedMap<K,V>

tailSet(fromElement:E) :SortedSet<E>

subMap(from:K,to:K) :SortedMap<K,V>

subSet(from:E, to:E) :SortedSet<E>

For example, headMap(toKey) returns a SortedMap of map entries corresponding to the keys that are strictly less than toKey, {x|x<toKey}.

3. (Optional) As shown in the class diagram above on the right, a TreeMap inherits methods from NavigableMap that are analogous to the methods TreeSet inherits from NavigableSet:

TreeMap (NavigableMap) TreeSet (NavigableSet)floorKey(key:K):K floor(e:E):ElowerKey(key:K):K lower(e:E):EceilingKey(key:K):K ceiling(e:E) :EhigherKey(key:K):K higher(e:E):E

For example, floorKey(key) returns the greatest key less than or equal to the given key, or null if there is no such key.

4. Example – Similar to an example earlier when we covered HashMap, we can create a TreeMap of Employee objects where the keys are ordered.

// Create mapTreeMap<Integer,Employee> tmEmployees = new TreeMap<>();

// Create employeesEmployee e1 = new Employee("Lyton", "Xavier", 243558673, 77.88);...

// Put employee in maptmEmployees.put(e1.getSSNum(), e1);...

5. A TreeMap can be created from another Map using this constructor:

TreeMap(m:Map<? extends K, ? extends V>)

8

Page 9: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

6. A TreeMap also supports a putAll method that accepts a Map and adds all the map entries in the argument, whose key does not exist in this map, to this map:

putAll(Map<? extends K,? extends V> map)

Practice Problems

For the next several problems: Suppose you have a LoginAccount class (code available in previous homework) with the following string fields (and associated getters): userId, password, name.

5. Given that you have a HashMap of LoginAccounts named hmAccounts where userId is the key. Write a snippet of code to create a TreeMap named tmAccounts which is the same as hmAccounts except the keys are ordered.

6. Write a method, getPasswords that accepts a TreeMap of LoginAccounts and returns a list of the passwords.

7. Write a method, getPasswords2 that accepts a TreeMap of LoginAccounts and returns a set of the unique passwords.

8. Write a method, removeAccounts that accepts a TreeMap of LoginAccounts and removes accounts where the userID doesn’t contain the “@” symbol. This method does not return anything

9. Write a static method, swapKeyValue that accepts a TreeMap where the key is a character and the value is an integer. The method should return a TreeMap where the key is an integer and the value is a string. The method should swap the key and value from the input map such that if a value occurs more than once in the input map, then the corresponding keys are concatenated to form the value for the output map. For example:

Input Output

Key ValueA 8B 2C 4G 2L 8P 2R 1V 3

Key Value1 R2 BGP3 V4 C8 AL

Note in the input map that the value 8 occurs twice. Thus, the output map has a key of 8 and the value is “AL”. The value 1 occurs in the input map only once, so the key-value pair in the output map is: 1-“R”

9

Page 10: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

Section 21.13 – Case Study: Occurrences of Words

1. Example – Presented slightly different from the text. Write a method, getWordOccurrences that accepts a string and returns a TreeMap of the distinct words in the string and number of occurrences of each.

A sample call to method:

public static void main(String[] args) {String sentence = "The only people for me are the mad (mad mad) ones, "

+ "the: ones who are mad to live, mad to talk";

String[] wordsAry = sentence.split("[ \n\t\r.,;:!?(){]");

List<String> words = new ArrayList<>(Arrays.asList(wordsAry));

TreeMap<String,Integer> tmOccurrences = getWordOccurrences(words);

System.out.println(tmOccurrences);

}

The output:

{are=2, for=1, live=1, mad=5, me=1, ones=2, only=1, people=1, talk=1, the=3, to=2, who=1}

2. Solution – The code is found on the Schedule.

public static TreeMap<String,Integer> getWordOccurrences(List<String> words) {TreeMap<String,Integer> tmOccurrences = new TreeMap<>();for(String word : words) {

if(word.length()>0) {String lcWord = word.toLowerCase();if(!tmOccurrences.containsKey(lcWord)) {

tmOccurrences.put(lcWord, 1);}else {

int count = tmOccurrences.get(lcWord);tmOccurrences.put(lcWord, ++count);

}}

}return tmOccurrences;

}

Homework

OMIT THESE PROBLEMS

For the next several problems: Suppose you have a LoginAccount class with the following string fields (and associated getters): userId, password, name, and double field: balance.

10. We desire a method, getSortedList that accepts a Map that contains words as the keys and counts as the values (for example, the output from getWordOccurrences in Section 21.6 notes above)and returns some

10

Page 11: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

type of collection that orders the words on their occurrence and if two words have the same occurrence than ordered on the word. For example:

Input Ouputa-2and-1class-1day-1good-3have-1time-1

and: 1class: 1day: 1have: 1time: 1a: 2good: 3

a. Why is a TreeMap not the correct return type for this method?b. Write this method. Hints:

i. Write a class, WordOccurrence that holds the word and the count and also implements Comparable as described (order on count, and if tied, then order on word).

ii. Create either TreeSet of WordOccurrencesiii. Loop over the words in the keyset and for each word, create a WordOccurrence with the word

and count and then add the WordOccurrence to the TreeSetiv. Return the TreeSet.

Alternately, instead of returning a TreeSet, you could return a list of WordOccurrences that your sort before returning.

11

Page 12: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

Ch 20 & 21, JCF Summary

12

Page 13: mypages.valdosta.edu · Web viewCS 1302 – Chapter 21. Maps. These notes are almost identical to the lab, except for one section: 21.10. There, we present an example that continues

13


Recommended