2
2
3
3
import java .io .FileNotFoundException ;
4
4
import java .io .FileReader ;
5
- import java .util .Map ;
6
- import java .util .Iterator ;
7
- import java .util .LinkedHashMap ;
8
- import java .util .Scanner ;
9
- import static java .util .stream .Collectors .toMap ;
5
+ import java .util .*;
10
6
11
7
public class WC {
12
-
8
+
13
9
private Iterator <String > si ;
14
10
private Map <String , Integer > wordsWithCounts = new LinkedHashMap <>();
15
11
@@ -23,30 +19,47 @@ public WC(String fileName) {
23
19
}
24
20
25
21
public WC (Iterator <String > si ) {
22
+ this .wordsWithCounts = new LinkedHashMap <String , Integer >();
26
23
this .si = si ;
27
24
}
28
25
29
- public void wordCount () {
26
+ public Map <String , Integer > readWords () {
27
+
30
28
while (si .hasNext ()) {
31
- String current = si .next ().toLowerCase ().replaceAll ("[a-zñáéíóú]" , "" ); // deletes all other special characters and replaces them w blank space
29
+ String current = si .next ().toLowerCase ().replaceAll ("[^ a-zñáéíóú]" , "" ); // deletes all other special characters and replaces them w blank space
32
30
if (wordsWithCounts .containsKey (current )) {
33
31
wordsWithCounts .put (current , wordsWithCounts .get (current ) + 1 ); // if we have this word -> get the int value at that key and add one
34
- } else {
32
+ } else
35
33
wordsWithCounts .put (current , 1 ); // if we do not have the word, add it and set the count to one
36
- }
37
34
}
35
+ return wordsWithCounts ;
38
36
}
39
37
40
- public void print (){
38
+ public void reverseOrder (){
39
+ // Map<String, Integer> sorted = readWords().entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
40
+ // .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
41
+ // return sorted;
41
42
this .wordsWithCounts .entrySet ()
42
43
.stream ()
43
44
.sorted (Map .Entry .<String , Integer >comparingByValue ().reversed ())
44
45
.forEach (System .out ::println );
45
46
}
46
47
47
- public static void main (String [] args ){
48
- WC wc = new WC ("/Users/jessicacampbell/Dev/EncapsulativeCharacters/src/main/resources/DonQuijote.txt" );
49
- wc .print ();
50
- }
48
+ // public String display(){
49
+ // readWords();
50
+ // reverseOrder();
51
+ // StringBuilder sb = new StringBuilder();
52
+ // for(String key : wordsWithCounts.keySet()){
53
+ // sb.append("\nWord: " + key + "\nCount:" + wordsWithCounts.get(key) + "\n__________");
54
+ // }
55
+ // System.out.println(sb.toString());
56
+ // return sb.toString();
57
+ // }
58
+
59
+ public static void main (String [] args ) {
60
+ WC wc = new WC ("/Users/jessicacampbell/Dev/CR-MesoLabs-Collections-EncapsulativeCharacters/src/main/resources/DonQuijote.txt" );
61
+ wc .readWords ();
62
+ wc .reverseOrder ();
63
+ }
51
64
52
65
}
0 commit comments