Java Reference
In-Depth Information
31 // Get key and value from each entry
32 for (Map.Entry<String, Integer> entry: entrySet)
33 System.out.println(entry.getValue() + "\t" + entry.getKey());
34 }
35 }
display entry
a 2
class 1
fun 1
good 3
have 3
morning 1
visit 1
The program creates a TreeMap (line 10) to store pairs of words and their occurrence counts.
The words serve as the keys. Since all values in the map must be stored as objects, the count
is wrapped in an Integer object.
The program extracts a word from a text using the split method (line 12) in the String
class (see Section 10.10.4). For each word extracted, the program checks whether it is already
stored as a key in the map (line 17). If not, a new pair consisting of the word and its initial
count ( 1 ) is stored in the map (line 18). Otherwise, the count for the word is incremented by
1 (lines 21-23).
The program obtains the entries of the map in a set (line 29), and traverses the set to display
the count and the key in each entry (lines 32-33).
Since the map is a tree map, the entries are displayed in increasing order of words. To
display them in ascending order of the occurrence counts, see Programming Exercise 21.8.
Now sit back and think how you would write this program without using map. Your new
program would be longer and more complex. You will find that map is a very efficient and
powerful data structure for solving problems such as this.
21.21
Will the CountOccurrenceOfWords program work if line 10 is changed to
Check
Point
Map<String, int > map = new TreeMap<>();
21.22 Will the CountOccurrenceOfWords program work if line 17 is changed to
if (map.get(key) == null ) {
21.23 Will the CountOccurrenceOfWords program work if lines 32-33 are changed to
for (String key: map)
System.out.println(key + "\t" + map.getValue(key));
21.7 Singleton and Unmodifiable Collections and Maps
You can create singleton sets, lists, and maps and unmodifiable sets, lists, and maps
using the static methods in the Collections class.
Key
Point
The Collections class contains the static methods for lists and collections. It also contains
the methods for creating immutable singleton sets, lists, and maps, and for creating read-only
sets, lists, and maps, as shown in Figure 21.7.
The Collections class defines three constants— EMPTY_SET , EMPTY_LIST , and
EMPTY_MAP —for an empty set, an empty list, and an empty map. These collections are immu-
table. The class also provides the singleton(Object o) method for creating an immutable
set containing only a single item, the singletonList(Object o) method for creating
 
 
 
Search WWH ::




Custom Search