Skip to content

Instantly share code, notes, and snippets.

@hatone
Created November 12, 2016 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hatone/e86a47e0a8929470105743af43a904f1 to your computer and use it in GitHub Desktop.
Save hatone/e86a47e0a8929470105743af43a904f1 to your computer and use it in GitHub Desktop.
Word Count Engine
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;
}
}
@Ranjan-Raju
Copy link

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!"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment