// // Example of using various Collection classes, and Collections class. // // Usage: // java CharCount somestring // // Description: // Counts how many times each character in "somestring" appears. // // Example of use: // java CharCount "hello, world, how are you?" // import java.util.*; public class CharCount { public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: CharCount string"); System.exit(1); } Map map = new HashMap(); for (int i = 0 ; i < args[0].length(); ++i) { Character c = new Character(args[0].charAt(i)); Object o = map.get(c); if (o == null) map.put(c, new Integer(1)); else { int count = ((Integer) o).intValue(); map.put(c, new Integer(count + 1)); } } List chars = new ArrayList(map.keySet()); Collections.sort(chars); Iterator iter = chars.iterator(); while (iter.hasNext()) { Object key = iter.next(); System.out.println(key + ": " + map.get(key)); } } }