123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package io.zipcoder;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileReader;
  4. import java.util.*;
  5. public class WC {
  6. private Iterator<String> si;
  7. public WC(String fileName) {
  8. try {
  9. Scanner scanner = new Scanner(new FileReader(fileName));
  10. scanner.useDelimiter("[\\p{Punct}\\s]+");
  11. this.si = scanner;
  12. } catch (FileNotFoundException e) {
  13. System.out.println(fileName + " Does Not Exist");
  14. System.exit(-1);
  15. }
  16. }
  17. // public WC(Iterator<String> si) {
  18. // this.si = si;
  19. //
  20. // }
  21. //
  22. // public Iterator<String> getSi() {
  23. //
  24. // return si;
  25. // }
  26. public HashMap<String, Integer> readFile() {
  27. HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
  28. while(si.hasNext()) {
  29. String key = si.next().toLowerCase();
  30. if(wordCount.containsKey(key)) {
  31. int value = wordCount.get(key);
  32. value++;
  33. wordCount.put(key, value);
  34. } else {
  35. wordCount.put(key, 1);
  36. }
  37. }
  38. return wordCount;
  39. }
  40. public static void printWordCount(HashMap<String, Integer> myMap) {
  41. for (String word: myMap.keySet()){
  42. String key = word;
  43. String value = myMap.get(word).toString();
  44. System.out.println(key + ": " + value);
  45. }
  46. }
  47. public static LinkedHashMap<String, Integer> sortList(HashMap<String, Integer> myMap) {
  48. List<String> mapKeys = new ArrayList<String>(myMap.keySet());
  49. List<Integer> mapValues = new ArrayList<Integer>(myMap.values());
  50. Collections.sort(mapValues);
  51. Collections.sort(mapKeys);
  52. LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
  53. Iterator<Integer> valueIt = mapValues.iterator();
  54. while (valueIt.hasNext()) {
  55. Integer val = valueIt.next();
  56. Iterator<String> keyIt = mapKeys.iterator();
  57. while (keyIt.hasNext()) {
  58. String key = keyIt.next();
  59. Integer comp1 = myMap.get(key);
  60. Integer comp2 = val;
  61. if (comp1.equals(comp2)) {
  62. keyIt.remove();
  63. sortedMap.put(key, val);
  64. break;
  65. }
  66. }
  67. }
  68. return sortedMap;
  69. // Map<String, Integer> sorted = myMap
  70. // .entrySet()
  71. // .stream()
  72. // .sorted(comparingByValue())
  73. // .collect(
  74. // toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2,
  75. // LinkedHashMap::new));
  76. }
  77. public static void main(String[] args) {
  78. String fileName = "./../../LittleWomen.txt";
  79. String fullPath = WC.class.getResource(fileName).getFile();
  80. WC wc = new WC(fullPath);
  81. HashMap<String, Integer> result = wc.readFile();
  82. printWordCount(sortList(result));
  83. }
  84. }