Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@EmilHernvall
Created May 3, 2011 17:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save EmilHernvall/953748 to your computer and use it in GitHub Desktop.
Save EmilHernvall/953748 to your computer and use it in GitHub Desktop.
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
Copy link

JonasCz commented Apr 4, 2015

Very nice !

@mephisto6
Copy link

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