Created
May 3, 2011 17:15
-
-
Save EmilHernvall/953748 to your computer and use it in GitHub Desktop.
Find the most popular words in a file - Java version
This file contains hidden or 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.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"); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...