// Answer to exercise 5.1 import java.util.*; class CollectionTest { public static void main(String[] args) { LinkedList list = Story.getTextAsLinkedList(); // The getTextAsLinkedList() can return a ' as a single word. // We will ignore that, and just treat it as a word. // ex a System.out.println("# words: " + list.size()); // ex b System.out.println("word at pos 45: " + list.get(45)); // ex c Set set = new TreeSet(list); System.out.println("\n# different words: " + set.size()); // ex d System.out.println("\n\nAll the words in alphabetic order\n" + "---------------------------------"); // an iterator of a treeset iterates the elements in natural // order - which for strings is sorted as we want. Iterator it = set.iterator(); while(it.hasNext()) System.out.print(it.next() + " "); // ex e System.out.println("\n\nPrinting all the words again\n" + "-----------------------------"); // We use an arraylist instead to make the sorting faster. ArrayList al = new ArrayList(list); Collections.sort(al); it = al.iterator(); while(it.hasNext()) System.out.print(it.next() + " "); // ex f System.out.println("\n\nPrinting all the words and frequency\n" + "------------------------------------"); SortedMap map = new TreeMap(); it = list.iterator(); // first add all elements to a map, where the key is the word // so identical words become identical keys while(it.hasNext()) { String word = (String) it.next(); Integer i; // does an entry already exist? if(map.containsKey(word)) i = (Integer) map.get(word); // get the count else i = new Integer(0); map.put(word, new Integer(i.intValue()+1) ); } // now print all keys (the words) and their counts... set = map.entrySet(); it = set.iterator(); while(it.hasNext()) { Map.Entry i = (Map.Entry) it.next(); System.out.print("["+ i.getKey() + ", " + i.getValue()+"] "); } // g // fetch all the elements and put them in a list it = list.iterator(); System.out.println("\n\nPrinting all longer than 6 characters\n"); while(it.hasNext()) { String word = (String)it.next(); if ( word.length() > 6 ) System.out.print(word + " "); } } }