词频统计
hello hadoop hello spark
i love you hadoop and spark
i learn hadoop and scala
编程实现
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
public class WordCount {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
Map<String, Integer> wc = new HashMap<>();
String nextLine = "";
while ((nextLine = br.readLine()) != null) {
String[] words = nextLine.split(" ");
for (String word: words) {
wc.put(word, wc.containsKey(word)? wc.get(word) + 1 : 1);
}
}
for (String key : wc.keySet()) {
System.out.println("(" + key + "," + wc.get(key) + ")");
}
}
}