package io.zipcoder; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.*; public class WC { private Iterator si; public WC(String fileName) { try { Scanner scanner = new Scanner(new FileReader(fileName)); scanner.useDelimiter("[\\p{Punct}\\s]+"); this.si = scanner; } catch (FileNotFoundException e) { System.out.println(fileName + " Does Not Exist"); System.exit(-1); } } // public WC(Iterator si) { // this.si = si; // // } // // public Iterator getSi() { // // return si; // } public HashMap readFile() { HashMap wordCount = new HashMap(); while(si.hasNext()) { String key = si.next().toLowerCase(); if(wordCount.containsKey(key)) { int value = wordCount.get(key); value++; wordCount.put(key, value); } else { wordCount.put(key, 1); } } return wordCount; } public static void printWordCount(HashMap myMap) { for (String word: myMap.keySet()){ String key = word; String value = myMap.get(word).toString(); System.out.println(key + ": " + value); } } public static LinkedHashMap sortList(HashMap myMap) { List mapKeys = new ArrayList(myMap.keySet()); List mapValues = new ArrayList(myMap.values()); Collections.sort(mapValues); Collections.sort(mapKeys); LinkedHashMap sortedMap = new LinkedHashMap(); Iterator valueIt = mapValues.iterator(); while (valueIt.hasNext()) { Integer val = valueIt.next(); Iterator keyIt = mapKeys.iterator(); while (keyIt.hasNext()) { String key = keyIt.next(); Integer comp1 = myMap.get(key); Integer comp2 = val; if (comp1.equals(comp2)) { keyIt.remove(); sortedMap.put(key, val); break; } } } return sortedMap; // Map sorted = myMap // .entrySet() // .stream() // .sorted(comparingByValue()) // .collect( // toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2, // LinkedHashMap::new)); } public static void main(String[] args) { String fileName = "./../../LittleWomen.txt"; String fullPath = WC.class.getResource(fileName).getFile(); WC wc = new WC(fullPath); HashMap result = wc.readFile(); printWordCount(sortList(result)); } }