1、加载文件,获取文件中的内容(一次读一行,存入到StringBuilder中)
2、获取文件中所有的单词(使用正则表达式),得到String[]数组
3、将单词和出现的次数存入到map中
4、统计map中最大的value值
5、遍历map中的key,将值与value相同的key存入到list中。
6、这样就找到了出现次数最多的单词。
代码如下:
public class Test5 {
public static String loadFile(String path){
StringBuilder str = new StringBuilder();
try {
Reader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
String line = null;
while((line=br.readLine())!=null){
str.append(line);
}
br.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return str.toString();
}
public static String[] parseWords(String string){
String[] str = string.split("[^a-zA-Z]+");
return str;
}
public static Map countWords(String[] strings){
Map<String,Integer> map = new HashMap<>();
for (String str:strings) {
if(map.containsKey(str)){
Integer n = map.get(str);
map.put(str,++n);
}else{
map.put(str,1);
}
}
return map;
}
public static Integer maxValue(Map<String,Integer> map){
Collection<Integer> c = map.values();
Integer n = Collections.max(c);
return n;
}
public static List getKeyByMaxValue(Map<String,Integer> map,Integer maxValue){
List<String> list = new ArrayList<>();
for (Map.Entry<String,Integer> entry:map.entrySet()) {
if(entry.getValue()==maxValue){
list.add(entry.getKey());
}
}
return list;
}
public static void main(String[] args) {
String str = loadFile("F://a.txt");
String[] strings = parseWords(str);
Map<String,Integer> map = countWords(strings);
Integer maxValue = maxValue(map);
List<String> list = getKeyByMaxValue(map,maxValue);
System.out.println(list.toString());
}
}