Collection Classes: Sets and Maps

 

Unit #13

 

 

Key Points:

 

1)    A Set is a built-in interface in the Collections library that stores distinct values of a given object.

2)    A TreeSet is a built-in class in the Collections library that implements the Set interface. All the values in a TreeSet are stored in ascending order.

3)    A Map is an interface in the Collections library that stores distinct values as “Keys” and the mapped values of the keys as “Values”. The object type for keys and values can either be the same or different. A simple example of a map would be a file which stores distinct values of login names under “Keys” and the corresponding passwords as “Values”. Hence, login names are always unique while passwords could be similar for two different login names.

4)    If a HashMap contains a key-value pair, (K, V) and another key-value pair, (K, V) is inserted, the first pair, (K, V) is replaced with the second pair (K, V).

5)    If a HashMap contains a key-value pair, (K, V) and another key-value pair, (K, V1) is inserted, the first pair, (K, V) is replaced with the second pair (K, V1).

6)    If a HashMap contains a key-value pair, (K, V) and another key-value pair, (K1, V) is inserted, both of these pairs are stored as two distinct entries as they have distinct “Keys” even though they have similar “Values”.

7)    The Hashmap only allows a single null value for “Keys” but has no limit on null values for “Values”.

8)    The values stored in a HashMap are not sorted.

9)    The values stored in the HashMap are not guaranteed to be in the order in which they were inserted to the HashMap.

 

 

 

 

Example Program: The following program takes a sentence as input. The program converts all the characters in the input sentence to lower case. A Hashmap is used to store the strings as “Keys” and the number of times each string occurs in the sentence (an integer) as “Values”. Further, using the Set interface and the TreeSet class, the values in the output are printed in increasing order of the “Keys”. NOTE:  The program below is described in Chapter19 – Collections on Pages 934-936 of the textbook, Java – How to Program, Seventh Edition by P.J Deitel and H.M.Deitel)

 

 

·       WordFrequency.java

 

 

Program Output:

Enter the sentence:

to be or not to be

 

Printing the Map.......

Keys           Values

be               2

not             1

or                1

to                2