CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections...

16
CS 1302 – Chapter 21 Maps We will cover Sections 1-6 in Chapter 21. Section 21.5 – 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. 1

Transcript of CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections...

Page 1: CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections 1-6 in Chapter 21. Section 21.5 – Maps. Frequently, it is convenient to associate

CS 1302 – Chapter 21Maps

We will cover Sections 1-6 in Chapter 21.

Section 21.5 – 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: CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections 1-6 in Chapter 21. Section 21.5 – Maps. Frequently, it is convenient to associate

Section 21.5.1 – 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. Thus, we can call any Collection methods on names.

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:

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

}

2

Page 3: CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections 1-6 in Chapter 21. Section 21.5 – Maps. Frequently, it is convenient to associate

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: CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections 1-6 in Chapter 21. Section 21.5 – Maps. Frequently, it is convenient to associate

Homework

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: CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections 1-6 in Chapter 21. Section 21.5 – Maps. Frequently, it is convenient to associate

Section 21.5.1 – Example

See the example in the code download on the Schedule which shows a one-to-many relationship implemented with a map.

Section 21.5.2 – The LinkedHashMap Class

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.

5

Page 6: CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections 1-6 in Chapter 21. Section 21.5 – Maps. Frequently, it is convenient to associate

Section 21.5.3 – 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>)

6

Page 7: CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections 1-6 in Chapter 21. Section 21.5 – Maps. Frequently, it is convenient to associate

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)

Homework

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”

7

Page 8: CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections 1-6 in Chapter 21. Section 21.5 – Maps. Frequently, it is convenient to associate

Section 21.6 – Case Study: Occurrences of Words

1. Study the example from the text carefully. Problem: count the occurrences of words in a string of text.

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

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;

}

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}

8

Page 9: CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections 1-6 in Chapter 21. Section 21.5 – Maps. Frequently, it is convenient to associate

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 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.

Sections 21.7 – Singleton & Unmodifiable Collections & Maps

Omit

9

Page 10: CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections 1-6 in Chapter 21. Section 21.5 – Maps. Frequently, it is convenient to associate

Ch 20 & 21, JCF Summary

10

Page 11: CS 1301 – Ch 6, Handout 1€¦  · Web viewCS 1302 – Chapter 21. Maps. We will cover Sections 1-6 in Chapter 21. Section 21.5 – Maps. Frequently, it is convenient to associate

11