基于Map的频率统计
1.实现代码
package com.java.domin;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class TableNumCount {
public static String read(String infile) throws IOException{
//使用IO流读取文件中的键
BufferedReader in = new BufferedReader(new FileReader(infile));
StringBuffer sbr = new StringBuffer();
String s;
Map<String, Integer> map = new HashMap<String, Integer>();
while( (s = in.readLine()) != null){//获取当前键
sbr.append(s +"\n");
Integer val = map.get(s); //获取当前键的频数
if(val == null)
map.put(s, new Integer(1)); //若当前键(及值)尚不存在,则该键频数为1,并添加到map中
else
map.put(s, val+1);//当前键已存在,在当前频数基础上加1
}
for(String key : map.keySet()){
if(map.get(key)==2) //如果键的频数大于等于2,则打印到控制台。
System.out.println(key);
}
in.close();
return sbr.toString();
}
public static void main(String[] args) throws IOException {
String infile = "D:\\tablecounts.txt";
read(infile);
}
}