| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- package io.zipcoder;
-
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.util.*;
-
- public class WC {
-
-
- private Iterator<String> 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<String> si) {
- // this.si = si;
- //
- // }
- //
- // public Iterator<String> getSi() {
- //
- // return si;
- // }
-
-
- public HashMap<String, Integer> readFile() {
- HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
-
- 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<String, Integer> myMap) {
- for (String word: myMap.keySet()){
-
- String key = word;
- String value = myMap.get(word).toString();
- System.out.println(key + ": " + value);
-
-
- }
- }
-
- public static LinkedHashMap<String, Integer> sortList(HashMap<String, Integer> myMap) {
- List<String> mapKeys = new ArrayList<String>(myMap.keySet());
- List<Integer> mapValues = new ArrayList<Integer>(myMap.values());
- Collections.sort(mapValues);
- Collections.sort(mapKeys);
-
- LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
- Iterator<Integer> valueIt = mapValues.iterator();
- while (valueIt.hasNext()) {
- Integer val = valueIt.next();
- Iterator<String> 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<String, Integer> 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<String, Integer> result = wc.readFile();
- printWordCount(sortList(result));
-
-
-
- }
-
- }
|