code_junkie

Which data structure would you use: TreeMap or HashMap? (Java)

Nov 12th, 2011
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. Word Frequency
  2. a 1
  3. and 5
  4. appearances 1
  5. as 1
  6. .
  7. .
  8. .
  9.  
  10. bag.add("big")
  11. bag.add("small")
  12. bag.add("big")
  13. int count = bag.getCount("big")
  14.  
  15. class Counter {
  16.  
  17. public static void main(String... argv)
  18. throws Exception
  19. {
  20. FileChannel fc = new FileInputStream(argv[0]).getChannel();
  21. ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
  22. CharBuffer cb = Charset.defaultCharset().decode(bb);
  23. Pattern p = Pattern.compile("[^ trnf.,!?:;"()']+");
  24. Map<String, Integer> counts = new TreeMap<String, Integer>();
  25. Matcher m = p.matcher(cb);
  26. while (m.find()) {
  27. String word = m.group();
  28. Integer count = counts.get(word);
  29. count = (count == null) ? 1 : count + 1;
  30. counts.put(word, count);
  31. }
  32. fc.close();
  33. for (Map.Entry<String, Integer> e : counts.entrySet()) {
  34. System.out.printf("%s: %d%n", e.getKey(), e.getValue());
  35. }
  36. }
  37.  
  38. }
Add Comment
Please, Sign In to add comment