Created
November 12, 2016 02:57
-
-
Save hatone/e86a47e0a8929470105743af43a904f1 to your computer and use it in GitHub Desktop.
Word Count Engine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Map.Entry; | |
public class Main { | |
public static void main(String[] args) { | |
System.out.println("hello"); | |
sortMap(wordCount("practice makes perfect. get perfect by practice. just practice!")); | |
} | |
static HashMap<String,Integer> wordCount(String s) { | |
HashMap<String,Integer> answer = new HashMap<String,Integer>(); | |
String[] words = s.replace("!","").replace(".","").split(" "); | |
for(int i=0; i< words.length; i++) { | |
Integer c = answer.get(words[i]); | |
if(c == null) c = 0; | |
answer.put(words[i], c+1); | |
} | |
System.out.println(answer); | |
return answer; | |
} | |
static Map<String,Integer> sortMap( Map<String,Integer> m) { | |
List<Entry<String, Integer>> entries = new ArrayList<Entry<String, Integer>>(m.entrySet()); | |
Collections.sort(entries, new Comparator<Entry<String, Integer>>() { | |
@Override | |
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { | |
return o2.getValue().compareTo(o1.getValue()); | |
} | |
}); | |
return m; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good effort, however, this doesn't take care of other punctuations. What if the input was "do you practice? *actually makes perfect. get perfect by practice. just practice!"