Skip to content

Instantly share code, notes, and snippets.

@soltrinox
Created March 4, 2015 01:52
Show Gist options
  • Select an option

  • Save soltrinox/0db92cab0bef23cff890 to your computer and use it in GitHub Desktop.

Select an option

Save soltrinox/0db92cab0bef23cff890 to your computer and use it in GitHub Desktop.
Find the three most common words in a file. WordCounts.java
import java.util.Scanner;
import java.util.Map;
import java.util.TreeMap;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Comparator;
import java.util.Iterator;
public class WordCounts {
public static void main(String args[]) {
try{
String text = new Scanner( new File("words.txt") ).useDelimiter("\\A").next();
String[] words = text.toLowerCase().split("\\s+");
Map<String, Integer> wordCounts = new HashMap<String, Integer>();
for (String word : words) {
Integer count = wordCounts.get(word);
if (count == null) {
count = 0;
}
wordCounts.put(word, count + 1);
}
Map sortedMap = sortByValue(wordCounts);
//System.out.println(sortedMap);
Iterator iterator = sortedMap.entrySet().iterator();
int ii = 0;
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
if(ii < 3){
System.out.println("The word " + mapEntry.getKey()
+ " : occurs " + mapEntry.getValue() + " times");
ii++;
}
}
}catch(FileNotFoundException ex){
}
}
public static Map sortByValue(Map unsortedMap) {
Map sortedMap = new TreeMap(new ValueComparator(unsortedMap));
sortedMap.putAll(unsortedMap);
return sortedMap;
}
}
class ValueComparator implements Comparator {
Map map;
public ValueComparator(Map map) {
this.map = map;
}
public int compare(Object keyA, Object keyB) {
Comparable valueA = (Comparable) map.get(keyA);
Comparable valueB = (Comparable) map.get(keyB);
return valueB.compareTo(valueA);
}
}
@realitybytes01
Copy link
Copy Markdown

String text = new Scanner( new File("words.txt") ).useDelimiter("\A").next();
in this line of code what is the use of "\A"
Thanks

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