Java Reference
In-Depth Information
21.20
Show the output of the following code:
public class
Test {
public static void
main(String[] args) {
Map<String, String> map =
new
LinkedHashMap<>();
map.put(
"123"
,
"John Smith"
);
map.put(
"111"
,
"George Smith"
);
map.put(
"123"
,
"Steve Yao"
);
map.put(
"222"
,
"Steve Yao"
);
System.out.println(
"(1) "
+ map);
System.out.println(
"(2) "
+
new
TreeMap<String, String>(map));
}
}
This case study writes a program that counts the occurrences of words in a text and
displays the words and their occurrences in alphabetical order of the words.
Key
Point
The program uses a
TreeMap
to store an entry consisting of a word and its count. For
each word, check whether it is already a key in the map. If not, add an entry to the map
with the word as the key and value
1
. Otherwise, increase the value for the word (key)
by
1
in the map. Assume the words are case insensitive; e.g.,
Good
is treated the same
as
good
.
Listing 21.9 gives the solution to the problem.
L
ISTING
21.9
CountOccurrenceOfWords.java
1
import
java.util.*;
2
3
public class
CountOccurrenceOfWords {
4
public static void
main(String[] args) {
5
// Set text in a string
6 String text =
"Good morning. Have a good class. "
+
7
"Have a good visit. Have fun!"
;
8
9
// Create a TreeMap to hold words as key and count as value
10
Map<String, Integer> map =
new
TreeMap<>();
tree map
11
12 String[] words = text.split(
"[ \n\t\r.,;:!?(){"
);
13
split string
for
(
int
i =
0
; i < words.length; i++) {
14
String key = words[i].toLowerCase();
15
16
if
(key.length() >
0
) {
17
if
(!map.containsKey(key)) {
18
map.put(key,
1
);
add entry
19 }
20
else
{
21
int
value = map.get(key);
22 value++;
23
map.put(key, value);
update entry
24 }
25 }
26 }
27
28
// Get all entries into a set
29
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
entry set
30
Search WWH ::
Custom Search