Integer max = Collections.max(treeMap.values()); Set
Iterator
while (iterator.hasNext()) { Object key = iterator.next();
Integer value = (Integer)(treeMap.get(key)); if (value.equals(max)) {
System.out.println(\ + key + \); } } } }
21.7
import java.util.*;
public class Exercise21_07 {
public static void main(String[] args) { // Text in a string
String text = \ + \;
// Create a hash map to hold words and key and count as value HashMap
String[] tokens = text.split(\); for (String key: tokens) { if (hashMap.get(key) != null) {
hashMap.put(key, hashMap.get(key).intValue() + 1); } else {
if (key.trim().length() > 0) hashMap.put(key, 1); } }
// Get an entry set for the tree map
Set
ArrayList
for (Map.Entry
list.add(new WordOccurrence(entry.getKey(), entry.getValue())); }
Collections.sort(list);
for (WordOccurrence item: list) { System.out.println(item); } } }
class WordOccurrence implements Comparable
public WordOccurrence(String word, int count) { this.word = word; this.count = count; }
@Override
public int compareTo(WordOccurrence o) { return count - o.count; }
@Override
public boolean equals(Object o) {
return word.equals(((WordOccurrence)o).word); }
@Override
public String toString() { return word + \ + count; } }
21.8
import java.util.*; import java.io.*;
public class Exercise21_08 {
public static void main(String[] args) { if (args.length != 1) {
System.out.println(
\); System.exit(1); }
String filename = args[0];
// Create a tree map to hold words as key and count as value TreeMap
try {
Scanner input = new Scanner(new File(filename));
while (input.hasNext()) {
String line = input.nextLine();
String[] words = line.split(\);
for (int i = 0; i < words.length; i++) { if (words[i].trim().length() > 0 && words[i].trim().matches(\)) {
if (treeMap.get(key) != null) { int count = treeMap.get(key); count++;
treeMap.put(key, count); } else {
treeMap.put(key, 1); }
String key = words[i].toLowerCase();
} } } }
catch (Exception ex) { ex.printStackTrace(); }
// Get an entry set for the tree map
Set
// Display words in alphabetical order
System.out.println(\ + \);
for (Map.Entry
System.out.println(entry.getValue() + \ + entry.getKey()); } }
21.9
import java.util.*;
public class Exercise21_09 {
public static void main(String[] args) { String[][] stateCapital = { {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \},
{\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \}, {\, \},