Create a gist now

Instantly share code, notes, and snippets.

Find the most popular words in a file - Java version
import java.io.*;
import java.util.*;
public class wordcount
{
public static class Word implements Comparable<Word>
{
String word;
int count;
@Override
public int hashCode()
{
return word.hashCode();
}
@Override
public boolean equals(Object obj)
{
return word.equals(((Word)obj).word);
}
@Override
public int compareTo(Word b)
{
return b.count - count;
}
}
public static void main(String[] args)
throws IOException
{
long time = System.currentTimeMillis();
Map<String, Word> countMap = new HashMap<String, Word>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(args[0])));
String line;
while ((line = reader.readLine()) != null) {
String[] words = line.split("[^A-ZÅÄÖa-zåäö]+");
for (String word : words) {
if ("".equals(word)) {
continue;
}
Word wordObj = countMap.get(word);
if (wordObj == null) {
wordObj = new Word();
wordObj.word = word;
wordObj.count = 0;
countMap.put(word, wordObj);
}
wordObj.count++;
}
}
reader.close();
SortedSet<Word> sortedWords = new TreeSet<Word>(countMap.values());
int i = 0;
for (Word word : sortedWords) {
if (i > 10) {
break;
}
System.out.println(word.count + "\t" + word.word);
i++;
}
time = System.currentTimeMillis() - time;
System.out.println("in " + time + " ms");
}
}
@JonasCz
JonasCz commented Apr 4, 2015

Very nice !

@mephisto6

It is incorrect if you have multiple words with the same occurence. SortedMap uses compareTo and if you only use the count in that method, you will lose those words that have the same count...

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