package dk.itu.oop.lecture4; 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 LinkedList list2 = new LinkedList(set); Collections.sort(list2, new SizeCoparator()); it = list2.iterator(); System.out.println("\n\nPrinting all according to frequency\n"); while(it.hasNext()) { Map.Entry i = (Map.Entry) it.next(); System.out.print("["+ i.getKey() + ", " + i.getValue()+"] "); } } } class SizeCoparator implements Comparator { public int compare(Object o1, Object o2) { Map.Entry e1 = (Map.Entry) o1, e2 = (Map.Entry) o2; return ((Integer) e1.getValue()).intValue() - ((Integer) e2.getValue()).intValue(); } public boolean equals(Object obj) { return obj == this; } }